<?php
//registration-funcitons.php, wp-admin/admin-functions.php

require_once('wpclasses.php');
class wpadmin {
	private static $_Instance;

	private function __construct(){
		return $this;
	}

	public static function getInstance(){
		if(!self::$_Instance){
			self::$_Instance = new wpadmin();
		}
		return self::$_Instance;
	}

	/////////////////////////////////////////////////////////
	/////////////// modified wordress functions /////////////

	////// bookmark.php /////////

	/**
	 * Alias for edit_link()
	 *
	 * @return edit_link(null);
	 */
	function add_link() {
		return self::edit_link();
	}


	function edit_link( $link_id = '' ) {
		if (!wpbasic::current_user_can( 'manage_links' ))
		wpbasic::wp_die( __( 'Cheatin&#8217; uh?' ));

		$_POST['link_url'] = wpformat::wp_specialchars( $_POST['link_url'] );
		$_POST['link_url'] = wpcomment::clean_url($_POST['link_url']);
		$_POST['link_name'] = wpformat::wp_specialchars( $_POST['link_name'] );
		$_POST['link_image'] = wpformat::wp_specialchars( $_POST['link_image'] );
		$_POST['link_rss'] = wpcomment::clean_url($_POST['link_rss']);
		if ( 'N' != $_POST['link_visible'] )
		$_POST['link_visible'] = 'Y';

		if ( !empty( $link_id ) ) {
			$_POST['link_id'] = $link_id;
			return wpadmin::wp_update_link( $_POST);
		} else {
			return wpadmin::wp_insert_link( $_POST);
		}
	}

	function get_default_link_to_edit() {
		if ( isset( $_GET['linkurl'] ) )
		$link->link_url = wpcomment::clean_url( $_GET['linkurl']);
		else
		$link->link_url = '';

		if ( isset( $_GET['name'] ) )
		$link->link_name = wpcomment::attribute_escape( $_GET['name']);
		else
		$link->link_name = '';

		$link->link_visible = 'Y';

		return $link;
	}

	function wp_delete_link($link_id) {
		//global $wpdb;
		$wpdb = JWPBlog::getWpdb();

		wpbasic::do_action('delete_link', $link_id);

		wpadmin::wp_delete_object_term_relationships($link_id, 'link_category');

		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->links WHERE link_id = %d", $link_id) );

		wpbasic::do_action('deleted_link', $link_id);

		return true;
	}

	function wp_get_link_cats($link_id = 0) {

		$cats = wpadmin::wp_get_object_terms($link_id, 'link_category', 'fields=ids');

		return array_unique($cats);
	}

	function get_link_to_edit( $link_id ) {
		return wpadmin::get_bookmark( $link_id, OBJECT, 'edit' );
	}

	function wp_insert_link($linkdata) {
		$wpdb = JWPBlog::getWpdb();
		$current_user = JWPBlog::getCurrentUser();

		$defaults = array('link_id' => 0, 'link_name' => '', 'link_url' => '', 'link_rating' => 0 );

		$linkdata = wpbasic::wp_parse_args($linkdata, $defaults);
		$linkdata = wpadmin::sanitize_bookmark($linkdata, 'db');

		extract(wpformat::stripslashes_deep($linkdata), EXTR_SKIP);

		$update = false;

		if ( !empty($link_id) )
		$update = true;

		if ( trim( $link_name ) == '' )
		return 0;

		if ( trim( $link_url ) == '' )
		return 0;

		if ( empty($link_rating) )
		$link_rating = 0;

		if ( empty($link_image) )
		$link_image = '';

		if ( empty($link_target) )
		$link_target = '';

		if ( empty($link_visible) )
		$link_visible = 'Y';

		if ( empty($link_owner) )
		$link_owner = $current_user->id;

		if ( empty($link_notes) )
		$link_notes = '';

		if ( empty($link_description) )
		$link_description = '';

		if ( empty($link_rss) )
		$link_rss = '';

		if ( empty($link_rel) )
		$link_rel = '';

		// Make sure we set a valid category
		if (0 == count($link_category) || !is_array($link_category)) {
			$link_category = array(wpbasic::get_option('default_link_category'));
		}

		if ( $update ) {
			$wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_url = %s,
			link_name = %s, link_image = %s, link_target = %s,
			link_visible = %s, link_description = %s, link_rating = %s,
			link_rel = %s, link_notes = %s, link_rss = %s
			WHERE link_id = %s", $link_url, $link_name, $link_image, $link_target, $link_visible, $link_description, $link_rating, $link_rel, $link_notes, $link_rss, $link_id) );
		} else {
			$wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->links (link_url, link_name, link_image, link_target, link_description, link_visible, link_owner, link_rating, link_rel, link_notes, link_rss) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
			$link_url,$link_name, $link_image, $link_target, $link_description, $link_visible, $link_owner, $link_rating, $link_rel, $link_notes, $link_rss) );
			$link_id = (int) $wpdb->insert_id;
		}

		wpadmin::wp_set_link_cats($link_id, $link_category);

		if ( $update )
		wpbasic::do_action('edit_link', $link_id);
		else
		wpbasic::do_action('add_link', $link_id);

		return $link_id;
	}

	function wp_set_link_cats($link_id = 0, $link_categories = array()) {
		// If $link_categories isn't already an array, make it one:
		if (!is_array($link_categories) || 0 == count($link_categories))
		$link_categories = array(wpbasic::get_option('default_link_category'));

		$link_categories = array_map('intval', $link_categories);
		$link_categories = array_unique($link_categories);

		wpadmin::wp_set_object_terms($link_id, $link_categories, 'link_category');
	}	// wp_set_link_cats()

	function wp_update_link($linkdata) {
		$link_id = (int) $linkdata['link_id'];

		$link = wpadmin::get_link($link_id, ARRAY_A);

		// Escape data pulled from DB.
		$link = wpbasic::add_magic_quotes($link);

		// Passed link category list overwrites existing category list if not empty.
		if ( isset($linkdata['link_category']) && is_array($linkdata['link_category'])
		&& 0 != count($linkdata['link_category']) )
		$link_cats = $linkdata['link_category'];
		else
		$link_cats = $link['link_category'];

		// Merge old and new fields with new fields overwriting old ones.
		$linkdata = array_merge($link, $linkdata);
		$linkdata['link_category'] = $link_cats;

		return wpadmin::wp_insert_link($linkdata);
	}


	////////// comment.php ////////////////

	function comment_exists($comment_author, $comment_date) {
		$wpdb = JWPBlog::getWpdb();

		return $wpdb->get_var( $wpdb->prepare("SELECT comment_post_ID FROM $wpdb->comments
		WHERE comment_author = %s AND comment_date = %s", $comment_author, $comment_date) );
	}

	function edit_comment() {

		$comment_post_ID = (int) $_POST['comment_post_ID'];

		if (!current_user_can( 'edit_post', $comment_post_ID ))
		wp_die( __('You are not allowed to edit comments on this post, so you cannot edit this comment.' ));

		$_POST['comment_author'] = $_POST['newcomment_author'];
		$_POST['comment_author_email'] = $_POST['newcomment_author_email'];
		$_POST['comment_author_url'] = $_POST['newcomment_author_url'];
		$_POST['comment_approved'] = $_POST['comment_status'];
		$_POST['comment_content'] = $_POST['content'];
		$_POST['comment_ID'] = (int) $_POST['comment_ID'];

		foreach ( array ('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
			if ( !empty( $_POST['hidden_' . $timeunit] ) && $_POST['hidden_' . $timeunit] != $_POST[$timeunit] ) {
				$_POST['edit_date'] = '1';
				break;
			}
		}


		if (!empty ( $_POST['edit_date'] ) ) {
			$aa = $_POST['aa'];
			$mm = $_POST['mm'];
			$jj = $_POST['jj'];
			$hh = $_POST['hh'];
			$mn = $_POST['mn'];
			$ss = $_POST['ss'];
			$jj = ($jj > 31 ) ? 31 : $jj;
			$hh = ($hh > 23 ) ? $hh -24 : $hh;
			$mn = ($mn > 59 ) ? $mn -60 : $mn;
			$ss = ($ss > 59 ) ? $ss -60 : $ss;
			$_POST['comment_date'] = "$aa-$mm-$jj $hh:$mn:$ss";
		}

		wpcomment::wp_update_comment( $_POST);
	}

	function get_comment_to_edit( $id ) {
		$comment = wpbasic::get_comment($id);
		if( !$comment ){
			return false;
		}

		$comment->comment_ID = (int) $comment->comment_ID;
		$comment->comment_post_ID = (int) $comment->comment_post_ID;

		$comment->comment_content = format_to_edit( $comment->comment_content );
		$comment->comment_content = wpbasic::apply_filters( 'comment_edit_pre', $comment->comment_content);

		$comment->comment_author = wpformat::format_to_edit( $comment->comment_author );
		$comment->comment_author_email = wpformat::format_to_edit( $comment->comment_author_email );
		$comment->comment_author_url = wpcomment::clean_url($comment->comment_author_url);
		$comment->comment_author_url = wpformat::format_to_edit( $comment->comment_author_url );

		return $comment;
	}

	function get_pending_comments_num( $post_id ) {
		$wpdb = JWPBlog::getWpdb();

		$single = false;
		if ( !is_array($post_id) ) {
			$post_id = (array) $post_id;
			$single = true;
		}
		$post_id = array_map('intval', $post_id);
		$post_id = "'" . implode("', '", $post_id) . "'";

		//TODO: comments seems somehow ambigious, make reference a table class or object?
		$pending = $wpdb->get_results( "SELECT comment_post_ID, COUNT(comment_ID) as num_comments FROM $wpdb->comments WHERE comment_post_ID IN ( $post_id ) AND comment_approved = '0' GROUP BY comment_post_ID", ARRAY_N );

		if ( empty($pending) )
		return 0;

		if ( $single )
		return $pending[0][1];

		$pending_keyed = array();
		foreach ( $pending as $pend )
		$pending_keyed[$pend[0]] = $pend[1];

		return $pending_keyed;
	}

	// Add avatars to relevant places in admin, or try to

	function floated_admin_avatar( $name ) {
		$comment = JWPBlog::getComment();

		$id = $avatar = false;
		if ( $comment->comment_author_email )
		$id = $comment->comment_author_email;
		if ( $comment->user_id )
		$id = $comment->user_id;

		if ( $id )
		$avatar = wppluggin::get_avatar( $id, 32 );

		return "$avatar $name";
	}

	/* //TODO: what is this?
	 if ( is_admin() && ('edit-comments.php' == $pagenow || 'edit.php' == $pagenow) ) {
	 if ( get_option('show_avatars') )
		add_filter( 'comment_author', 'floated_admin_avatar' );
		}
		*/

	////////// file.php /////////////

	//TODO: what is this?
	/*
	$wp_file_descriptions = array ('index.php' => __( 'Main Index Template' ), 'style.css' => __( 'Stylesheet' ), 'rtl.css' => __( 'RTL Stylesheet' ), 'comments.php' => __( 'Comments' ), 'comments-popup.php' => __( 'Popup Comments' ), 'footer.php' => __( 'Footer' ), 'header.php' => __( 'Header' ), 'sidebar.php' => __( 'Sidebar' ), 'archive.php' => __( 'Archives' ), 'category.php' => __( 'Category Template' ), 'page.php' => __( 'Page Template' ), 'search.php' => __( 'Search Results' ), 'searchform.php' => __( 'Search Form' ), 'single.php' => __( 'Single Post' ), '404.php' => __( '404 Template' ), 'link.php' => __( 'Links Template' ), 'functions.php' => __( 'Theme Functions' ), 'attachment.php' => __( 'Attachment Template' ), 'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ), '.htaccess' => __( '.htaccess (for rewrite rules )' ),
	// Deprecated files
	'wp-layout.css' => __( 'Stylesheet' ), 'wp-comments.php' => __( 'Comments Template' ), 'wp-comments-popup.php' => __( 'Popup Comments Template' ));
	*/
	function get_file_description( $file ) {
		$wp_file_descriptions = JWPBlog::getFileDesc();

		if ( isset( $wp_file_descriptions[basename( $file )] ) ) {
			return $wp_file_descriptions[basename( $file )];
		}
		elseif ( file_exists( ABSPATH . $file ) && is_file( ABSPATH . $file ) ) {
			$template_data = implode( '', file( ABSPATH . $file ) );
			if ( preg_match( "|Template Name:(.*)|i", $template_data, $name ))
			return $name[1];
		}

		return basename( $file );
	}

	function get_home_path() {
		$home = wpbasic::get_option( 'home' );
		if ( $home != '' && $home != wpbasic::get_option( 'siteurl' ) ) {
			$home_path = parse_url( $home );
			$home_path = $home_path['path'];
			$root = str_replace( $_SERVER["PHP_SELF"], '', $_SERVER["SCRIPT_FILENAME"] );
			$home_path = wpformat::trailingslashit( $root.$home_path );
		} else {
			$home_path = ABSPATH;
		}

		return $home_path;
	}

	function get_real_file_to_edit( $file ) {
		if ('index.php' == $file || '.htaccess' == $file ) {
			$real_file = wpadmin::get_home_path() . $file;
		} else {
			$real_file = WP_CONTENT_DIR . $file;
		}

		return $real_file;
	}
	//$folder = Full path to folder
	//$levels = Levels of folders to follow, Default: 100 (PHP Loop limit)
	function list_files( $folder = '', $levels = 100 ) {
		if( empty($folder) )
		return false;

		if( ! $levels )
		return false;

		$files = array();
		if ( $dir = @opendir( $folder ) ) {
			while (($file = readdir( $dir ) ) !== false ) {
				if ( in_array($file, array('.', '..') ) )
				continue;
				if ( is_dir( $folder . '/' . $file ) ) {
					$files2 = wpbasic::list_files( $folder . '/' . $file, $levels - 1);
					if( $files2 )
					$files = array_merge($files, $files2 );
					else
					$files[] = $folder . '/' . $file . '/';
				} else {
					$files[] = $folder . '/' . $file;
				}
			}
		}
		@closedir( $dir );
		return $files;
	}

	function get_temp_dir() {
		if ( defined('WP_TEMP_DIR') )
		return wpformat::trailingslashit(WP_TEMP_DIR);

		$temp = WP_CONTENT_DIR . '/';
		if ( is_dir($temp) && is_writable($temp) )
		return $temp;

		if  ( function_exists('sys_get_temp_dir') )
		return wpformat::trailingslashit(sys_get_temp_dir());

		return '/tmp/';
	}

	function wp_tempnam($filename = '', $dir = ''){
		if ( empty($dir) )
		$dir = wpbasic::get_temp_dir();
		$filename = basename($filename);
		if ( empty($filename) )
		$filename = time();

		$filename = $dir . wpbasic::wp_unique_filename($dir, $filename);
		touch($filename);
		return $filename;
	}

	function validate_file_to_edit( $file, $allowed_files = '' ) {
		$file = stripslashes( $file );

		$code = wpadmin::validate_file( $file, $allowed_files );

		if (!$code )
		return $file;

		switch ( $code ) {
			case 1 :
				wpbasic::wp_die( __('Sorry, can&#8217;t edit files with ".." in the name. If you are trying to edit a file in your WordPress home directory, you can just type the name of the file in.' ));

			case 2 :
				wpbasic::wp_die( __('Sorry, can&#8217;t call files with their real path.' ));

			case 3 :
				wpbasic::wp_die( __('Sorry, that file cannot be edited.' ));
		}
	}

	// array wp_handle_upload ( array &file [, array overrides] )
	// file: reference to a single element of $_FILES. Call the function once for each uploaded file.
	// overrides: an associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
	// On success, returns an associative array of file attributes.
	// On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
	function wp_handle_upload( &$file, $overrides = false ) {
		// The default error handler.
		if (! function_exists( 'wp_handle_upload_error' ) ) {
			function wp_handle_upload_error( &$file, $message ) {
				return array( 'error'=>$message );
			}
		}

		// You may define your own function and pass the name in $overrides['upload_error_handler']
		$upload_error_handler = 'wp_handle_upload_error';

		// $_POST['action'] must be set and its value must equal $overrides['action'] or this:
		$action = 'wp_handle_upload';

		//TODO: replace with JText
		// Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
		$upload_error_strings = array( false,
		__( "The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
		__( "The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
		__( "The uploaded file was only partially uploaded." ),
		__( "No file was uploaded." ),
		__( "Missing a temporary folder." ),
		__( "Failed to write file to disk." ));

		// All tests are on by default. Most can be turned off by $override[{test_name}] = false;
		$test_form = true;
		$test_size = true;

		// If you override this, you must provide $ext and $type!!!!
		$test_type = true;
		$mimes = false;

		// Install user overrides. Did we mention that this voids your warranty?
		if ( is_array( $overrides ) )
		extract( $overrides, EXTR_OVERWRITE );

		// A correct form post will pass this test.
		if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
		return $upload_error_handler( $file, __( 'Invalid form submission.' ));

		// A successful upload will pass this test. It makes no sense to override this one.
		if ( $file['error'] > 0 )
		return $upload_error_handler( $file, $upload_error_strings[$file['error']] );

		// A non-empty file will pass this test.
		if ( $test_size && !($file['size'] > 0 ) )
		return $upload_error_handler( $file, __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini.' ));

		// A properly uploaded file will pass this test. There should be no reason to override this one.
		if (! @ is_uploaded_file( $file['tmp_name'] ) )
		return $upload_error_handler( $file, __( 'Specified file failed upload test.' ));

		// A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
		if ( $test_type ) {
			$wp_filetype = wpbasic::wp_check_filetype( $file['name'], $mimes );

			extract( $wp_filetype );

			if ( ( !$type || !$ext ) && !wpbasic::current_user_can( 'unfiltered_upload' ) )
			return $upload_error_handler( $file, __( 'File type does not meet security guidelines. Try another.' ));

			if ( !$ext )
			$ext = ltrim(strrchr($file['name'], '.'), '.');

			if ( !$type )
			$type = $file['type'];
		}

		// A writable uploads dir will pass this test. Again, there's no point overriding this one.
		if ( ! ( ( $uploads = wppost::wp_upload_dir() ) && false === $uploads['error'] ) )
		return $upload_error_handler( $file, $uploads['error'] );

		$filename = wpbasic::wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );

		// Move the file to the uploads dir
		$new_file = $uploads['path'] . "/$filename";
		if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) ) {
			return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
		}

		// Set correct file permissions
		$stat = stat( dirname( $new_file ));
		$perms = $stat['mode'] & 0000666;
		@ chmod( $new_file, $perms );

		// Compute the URL
		$url = $uploads['url'] . "/$filename";

		$return = wpbasic::apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) );

		return $return;
	}
	// Pass this function an array similar to that of a $_FILES POST array.
	function wp_handle_sideload( &$file, $overrides = false ) {
		// The default error handler.
		if (! function_exists( 'wp_handle_upload_error' ) ) {
			function wp_handle_upload_error( &$file, $message ) {
				return array( 'error'=>$message );
			}
		}

		// You may define your own function and pass the name in $overrides['upload_error_handler']
		$upload_error_handler = 'wp_handle_upload_error';

		// $_POST['action'] must be set and its value must equal $overrides['action'] or this:
		$action = 'wpadmin::wp_handle_sideload';

		// Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
		$upload_error_strings = array( false,
		__( "The file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
		__( "The file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
		__( "The file was only partially uploaded." ),
		__( "No file was sent." ),
		__( "Missing a temporary folder." ),
		__( "Failed to write file to disk." ));

		// All tests are on by default. Most can be turned off by $override[{test_name}] = false;
		$test_form = true;
		$test_size = true;

		// If you override this, you must provide $ext and $type!!!!
		$test_type = true;
		$mimes = false;

		// Install user overrides. Did we mention that this voids your warranty?
		if ( is_array( $overrides ) )
		extract( $overrides, EXTR_OVERWRITE );

		// A correct form post will pass this test.
		if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
		return $upload_error_handler( $file, __( 'Invalid form submission.' ));

		// A successful upload will pass this test. It makes no sense to override this one.
		if ( $file['error'] > 0 )
		return $upload_error_handler( $file, $upload_error_strings[$file['error']] );

		// A non-empty file will pass this test.
		if ( $test_size && !(filesize($file['tmp_name']) > 0 ) )
		return $upload_error_handler( $file, __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini.' ));

		// A properly uploaded file will pass this test. There should be no reason to override this one.
		if (! @ is_file( $file['tmp_name'] ) )
		return $upload_error_handler( $file, __( 'Specified file does not exist.' ));

		// A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
		if ( $test_type ) {
			$wp_filetype = wpbasic::wp_check_filetype( $file['name'], $mimes );

			extract( $wp_filetype );

			if ( ( !$type || !$ext ) && !wpbasic::current_user_can( 'unfiltered_upload' ) )
			return $upload_error_handler( $file, __( 'File type does not meet security guidelines. Try another.' ));

			if ( !$ext )
			$ext = ltrim(strrchr($file['name'], '.'), '.');

			if ( !$type )
			$type = $file['type'];
		}

		// A writable uploads dir will pass this test. Again, there's no point overriding this one.
		if ( ! ( ( $uploads = wppost::wp_upload_dir() ) && false === $uploads['error'] ) )
		return $upload_error_handler( $file, $uploads['error'] );

		$filename = wpbasic::wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );

		// Strip the query strings.
		$filename = str_replace('?','-', $filename);
		$filename = str_replace('&','-', $filename);

		// Move the file to the uploads dir
		$new_file = $uploads['path'] . "/$filename";
		if ( false === @ rename( $file['tmp_name'], $new_file ) ) {
			return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
		}

		// Set correct file permissions
		$stat = stat( dirname( $new_file ));
		$perms = $stat['mode'] & 0000666;
		@ chmod( $new_file, $perms );

		// Compute the URL
		$url = $uploads['url'] . "/$filename";

		$return = wpbasic::apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) );

		return $return;
	}

	/**
	 * Downloads a url to a local file using the Snoopy HTTP Class
	 *
	 * @param string $url the URL of the file to download
	 * @return mixed WP_Error on failure, string Filename on success.
	 */
	function download_url( $url ) {
		//WARNING: The file is not automatically deleted, The script must unlink() the file.
		if( ! $url )
		return new WP_Error('http_no_url', __('Invalid URL Provided'));

		$tmpfname = wpbasic::wp_tempnam($url);
		if( ! $tmpfname )
		return new WP_Error('http_no_file', __('Could not create Temporary file'));

		$handle = @fopen($tmpfname, 'w');
		if( ! $handle )
		return new WP_Error('http_no_file', __('Could not create Temporary file'));

		require_once( ABSPATH . 'wp-includes/class-snoopy.php' );
		$snoopy = new Snoopy();
		$snoopy->fetch($url);

		if( $snoopy->status != '200' ){
			fclose($handle);
			unlink($tmpfname);
			return new WP_Error('http_404', trim($snoopy->response_code));
		}
		fwrite($handle, $snoopy->results);
		fclose($handle);

		return $tmpfname;
	}

	function unzip_file($file, $to) {
		global $wp_filesystem;

		if ( ! $wp_filesystem || !is_object($wp_filesystem) )
		return new WP_Error('fs_unavailable', __('Could not access filesystem.'));

		$fs =& $wp_filesystem;

		require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');

		$archive = new PclZip($file);

		// Is the archive valid?
		if ( false == ($archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING)) )
		return new WP_Error('incompatible_archive', __('Incompatible archive'), $archive->errorInfo(true));

		if ( 0 == count($archive_files) )
		return new WP_Error('empty_archive', __('Empty archive'));

		$to = wpformat::trailingslashit($to);
		$path = explode('/', $to);
		$tmppath = '';
		for ( $j = 0; $j < count($path) - 1; $j++ ) {
			$tmppath .= $path[$j] . '/';
			if ( ! $fs->is_dir($tmppath) )
			$fs->mkdir($tmppath, 0755);
		}

		foreach ($archive_files as $file) {
			$path = explode('/', $file['filename']);
			$tmppath = '';

			// Loop through each of the items and check that the folder exists.
			for ( $j = 0; $j < count($path) - 1; $j++ ) {
				$tmppath .= $path[$j] . '/';
				if ( ! $fs->is_dir($to . $tmppath) )
				if ( !$fs->mkdir($to . $tmppath, 0755) )
				return new WP_Error('mkdir_failed', __('Could not create directory'), $to . $tmppath);
			}

			// We've made sure the folders are there, so let's extract the file now:
			if ( ! $file['folder'] )
			if ( !$fs->put_contents( $to . $file['filename'], $file['content']) )
			return new WP_Error('copy_failed', __('Could not copy file'), $to . $file['filename']);
			$fs->chmod($to . $file['filename'], 0644);
		}

		return true;
	}

	function copy_dir($from, $to) {
		$wp_filesystem =& JWPBlog::getFileSys();

		$dirlist = $wp_filesystem->dirlist($from);

		$from = trailingslashit($from);
		$to = trailingslashit($to);

		foreach ( (array) $dirlist as $filename => $fileinfo ) {
			if ( 'f' == $fileinfo['type'] ) {
				if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true) )
				return new WP_Error('copy_failed', __('Could not copy file'), $to . $filename);
				$wp_filesystem->chmod($to . $filename, 0644);
			} elseif ( 'd' == $fileinfo['type'] ) {
				if ( !$wp_filesystem->mkdir($to . $filename, 0755) )
				return new WP_Error('mkdir_failed', __('Could not create directory'), $to . $filename);
				$result = wpbasic::copy_dir($from . $filename, $to . $filename);
				if ( is_wp_error($result) )
				return $result;
			}
		}
	}

	//TODO: replace require
	function WP_Filesystem( $args = false ) {
		$wp_filesystem =& JWPBlog::getFileSys();

		require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');

		$method = wpbasic::get_filesystem_method();

		if ( ! $method )
		return false;

		$abstraction_file = wpbasic::apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-'.$method.'.php', $method);
		if( ! file_exists($abstraction_file) )
		return;

		require_once($abstraction_file);
		$method = "WP_Filesystem_$method";

		$wp_filesystem = new $method($args);

		if ( $wp_filesystem->errors->get_error_code() )
		return false;

		if ( !$wp_filesystem->connect() )
		return false; //There was an erorr connecting to the server.

		return true;
	}

	function get_filesystem_method() {
		$method = false;
		if( function_exists('getmyuid') && function_exists('fileowner') ){
			$temp_file = wpbasic::wp_tempnam();
			if ( getmyuid() == fileowner($temp_file) )
			$method = 'direct';
			unlink($temp_file);
		}

		if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext';
		if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
		return wpbasic::apply_filters('filesystem_method', $method);
	}

	/////////// image.php ////////////////

	/**
	 * File contains all the administration image manipulation functions.
	 *
	 * @package WordPress
	 */

	/**
	 * wp_create_thumbnail() - Create a thumbnail from an Image given a maximum side size.
	 *
	 * @package WordPress
	 * @param	mixed	$file	Filename of the original image, Or attachment id
	 * @param	int		$max_side	Maximum length of a single side for the thumbnail
	 * @return	string			Thumbnail path on success, Error string on failure
	 *
	 * This function can handle most image file formats which PHP supports.
	 * If PHP does not have the functionality to save in a file of the same format, the thumbnail will be created as a jpeg.
	 */
	function wp_create_thumbnail( $file, $max_side, $deprecated = '' ) {

		$thumbpath = image_resize( $file, $max_side, $max_side );
		return wpbasic::apply_filters( 'wp_create_thumbnail', $thumbpath );
	}

	/**
	 * wp_crop_image() - Crop an Image to a given size.
	 *
	 * @package WordPress
	 * @internal Missing Long Description
	 * @param	int	$src_file	The source file
	 * @param	int	$src_x		The start x position to crop from
	 * @param	int	$src_y		The start y position to crop from
	 * @param	int	$src_w		The width to crop
	 * @param	int	$src_h		The height to crop
	 * @param	int	$dst_w		The destination width
	 * @param	int	$dst_h		The destination height
	 * @param	int	$src_abs	If the source crop points are absolute
	 * @param	int	$dst_file	The destination file to write to
	 * @return	string			New filepath on success, String error message on failure
	 *
	 */
	function wp_crop_image( $src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
		if ( is_numeric( $src_file ) ) // Handle int as attachment ID
		$src_file = wppost::get_attached_file( $src_file );

		$src = wpadmin::wp_load_image( $src_file );

		if ( !is_resource( $src ))
		return $src;

		$dst = imagecreatetruecolor( $dst_w, $dst_h );

		if ( $src_abs ) {
			$src_w -= $src_x;
			$src_h -= $src_y;
		}

		if (function_exists('imageantialias'))
		imageantialias( $dst, true );

		imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );

		imagedestroy( $src ); // Free up memory

		if ( ! $dst_file )
		$dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );

		$dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );

		if ( imagejpeg( $dst, $dst_file ) )
		return $dst_file;
		else
		return false;
	}

	/**
	 * wp_generate_attachment_metadata() - Generate post Image attachment Metadata
	 *
	 * @package WordPress
	 * @internal Missing Long Description
	 * @param	int		$attachment_id	Attachment Id to process
	 * @param	string	$file	Filepath of the Attached image
	 * @return	mixed			Metadata for attachment
	 *
	 */
	function wp_generate_attachment_metadata( $attachment_id, $file ) {
		$attachment = get_post( $attachment_id );

		$metadata = array();
		if ( preg_match('!^image/!', wppost::get_post_mime_type( $attachment )) && wpadmin::file_is_displayable_image($file) ) {
			$imagesize = getimagesize( $file );
			$metadata['width'] = $imagesize[0];
			$metadata['height'] = $imagesize[1];
			list($uwidth, $uheight) = wpadmin::wp_shrink_dimensions($metadata['width'], $metadata['height']);
			$metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
			$metadata['file'] = $file;

			// make thumbnails and other intermediate sizes
			$sizes = array('thumbnail', 'medium');
			$sizes = wpbasic::apply_filters('intermediate_image_sizes', $sizes);

			foreach ($sizes as $size) {
				$resized = wpadmin::image_make_intermediate_size( $file, wpbasic::get_option("{$size}_size_w"), wpbasic::get_option("{$size}_size_h"), get_option("{$size}_crop") );
				if ( $resized )
				$metadata['sizes'][$size] = $resized;
			}

			// fetch additional metadata from exif/iptc
			$image_meta = wpadmin::wp_read_image_metadata( $file );
			if ($image_meta)
			$metadata['image_meta'] = $image_meta;

		}
		return wpbasic::apply_filters( 'wp_generate_attachment_metadata', $metadata );
	}

	/**
	 * wp_load_image() - Load an image which PHP Supports.
	 *
	 * @package WordPress
	 * @internal Missing Long Description
	 * @param	string	$file	Filename of the image to load
	 * @return	resource		The resulting image resource on success, Error string on failure.
	 *
	 */
	function wp_load_image( $file ) {
		if ( is_numeric( $file ) )
		$file = wppost::get_attached_file( $file );

		if ( ! file_exists( $file ) )
		return sprintf(__("File '%s' doesn't exist?"), $file);

		if ( ! function_exists('imagecreatefromstring') )
		return __('The GD image library is not installed.');

		// Set artificially high because GD uses uncompressed images in memory
		@ini_set('memory_limit', '256M');
		$image = imagecreatefromstring( file_get_contents( $file ) );

		if ( !is_resource( $image ) )
		return sprintf(__("File '%s' is not an image."), $file);

		return $image;
	}

	/**
	 * get_udims() - Calculated the new dimentions for downsampled images
	 *
	 * @package WordPress
	 * @internal Missing Description
	 * @see wp_shrink_dimensions()
	 * @param	int		$width	Current width of the image
	 * @param	int 	$height	Current height of the image
	 * @return	mixed			Array(height,width) of shrunk dimensions.
	 *
	 */
	function get_udims( $width, $height) {
		return wpadmin::wp_shrink_dimensions( $width, $height );
	}
	/**
	 * wp_shrink_dimensions() - Calculates the new dimentions for a downsampled image.
	 *
	 * @package WordPress
	 * @internal Missing Long Description
	 * @param	int		$width	Current width of the image
	 * @param	int 	$height	Current height of the image
	 * @param	int		$wmax	Maximum wanted width
	 * @param	int		$hmax	Maximum wanted height
	 * @return	mixed			Array(height,width) of shrunk dimensions.
	 *
	 */
	function wp_shrink_dimensions( $width, $height, $wmax = 128, $hmax = 96 ) {
		return wpadmin::wp_constrain_dimensions( $width, $height, $wmax, $hmax );
	}

	// convert a fraction string to a decimal
	function wp_exif_frac2dec($str) {
		@list( $n, $d ) = explode( '/', $str );
		if ( !empty($d) )
		return $n / $d;
		return $str;
	}

	// convert the exif date format to a unix timestamp
	function wp_exif_date2ts($str) {
		// seriously, who formats a date like 'YYYY:MM:DD hh:mm:ss'?
		@list( $date, $time ) = explode( ' ', trim($str) );
		@list( $y, $m, $d ) = explode( ':', $date );

		return strtotime( "{$y}-{$m}-{$d} {$time}" );
	}

	// get extended image metadata, exif or iptc as available
	function wp_read_image_metadata( $file ) {
		if ( !file_exists( $file ) )
		return false;

		list(,,$sourceImageType) = getimagesize( $file );

		// exif contains a bunch of data we'll probably never need formatted in ways that are difficult to use.
		// We'll normalize it and just extract the fields that are likely to be useful.  Fractions and numbers
		// are converted to floats, dates to unix timestamps, and everything else to strings.
		$meta = array(
		'aperture' => 0,
		'credit' => '',
		'camera' => '',
		'caption' => '',
		'created_timestamp' => 0,
		'copyright' => '',
		'focal_length' => 0,
		'iso' => 0,
		'shutter_speed' => 0,
		'title' => '',
		);

		// read iptc first, since it might contain data not available in exif such as caption, description etc
		if ( is_callable('iptcparse') ) {
			getimagesize($file, $info);
			if ( !empty($info['APP13']) ) {
				$iptc = iptcparse($info['APP13']);
				if ( !empty($iptc['2#110'][0]) ) // credit
				$meta['credit'] = utf8_encode(trim($iptc['2#110'][0]));
				elseif ( !empty($iptc['2#080'][0]) ) // byline
				$meta['credit'] = utf8_encode(trim($iptc['2#080'][0]));
				if ( !empty($iptc['2#055'][0]) and !empty($iptc['2#060'][0]) ) // created datee and time
				$meta['created_timestamp'] = strtotime($iptc['2#055'][0] . ' ' . $iptc['2#060'][0]);
				if ( !empty($iptc['2#120'][0]) ) // caption
				$meta['caption'] = utf8_encode(trim($iptc['2#120'][0]));
				if ( !empty($iptc['2#116'][0]) ) // copyright
				$meta['copyright'] = utf8_encode(trim($iptc['2#116'][0]));
				if ( !empty($iptc['2#005'][0]) ) // title
				$meta['title'] = utf8_encode(trim($iptc['2#005'][0]));
		 }
		}

		// fetch additional info from exif if available
		if ( is_callable('exif_read_data') && in_array($sourceImageType, wpbasic::apply_filters('wp_read_image_metadata_types', array(IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM)) ) ) {
			$exif = @exif_read_data( $file );
			if (!empty($exif['FNumber']))
			$meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
			if (!empty($exif['Model']))
			$meta['camera'] = trim( $exif['Model'] );
			if (!empty($exif['DateTimeDigitized']))
			$meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized']);
			if (!empty($exif['FocalLength']))
			$meta['focal_length'] = wp_exif_frac2dec( $exif['FocalLength'] );
			if (!empty($exif['ISOSpeedRatings']))
			$meta['iso'] = $exif['ISOSpeedRatings'];
			if (!empty($exif['ExposureTime']))
			$meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] );
		}
		// FIXME: try other exif libraries if available

		return wpbasic::apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );

	}

	// is the file a real image file?
	function file_is_valid_image($path) {
		$size = @getimagesize($path);
		return !empty($size);
	}

	// is the file an image suitable for displaying within a web page?
	function file_is_displayable_image($path) {
		$info = @getimagesize($path);
		if ( empty($info) )
		$result = false;
		elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) )
		// only gif, jpeg and png images can reliably be displayed
		$result = false;
		elseif ( $info['channels'] > 0 && $info['channels'] != 3 ) {
			// some web browsers can't display cmyk or grayscale jpegs
			$result = false;
		}
		else
		$result = true;

		return wpbasic::apply_filters('file_is_displayable_image', $result, $path);
	}

	////////// media.php //////////////////


	function media_upload_tabs() {
		$_default_tabs = array(
		'type' => __('Choose File'), // handler action suffix => tab text
		'gallery' => __('Gallery'),
		'library' => __('Media Library'),
		);

		return wpbasic::apply_filters('media_upload_tabs', $_default_tabs);
	}

	function update_gallery_tab($tabs) {
		$wpdb = JWPBlog::getWpdb();
		if ( !isset($_REQUEST['post_id']) ) {
			unset($tabs['gallery']);
			return $tabs;
		}
		if ( intval($_REQUEST['post_id']) )
		$attachments = intval($wpdb->get_var($wpdb->prepare("SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $_REQUEST['post_id'])));

		$tabs['gallery'] = sprintf(__('Gallery (%s)'), "<span id='attachments-count'>$attachments</span>");

		return $tabs;
	}

	//TODO: what is this?
	/*
	add_filter('media_upload_tabs', 'update_gallery_tab');
	*/

	function the_media_upload_tabs() {
		global $redir_tab;
		$tabs = wpadmin::media_upload_tabs();

		if ( !empty($tabs) ) {
			echo "<ul id='sidemenu'>\n";
			if ( isset($redir_tab) && array_key_exists($redir_tab, $tabs) )
			$current = $redir_tab;
			elseif ( isset($_GET['tab']) && array_key_exists($_GET['tab'], $tabs) )
			$current = $_GET['tab'];
			else {
				$keys = array_keys($tabs);
				$current = array_shift($keys);
			}
			foreach ( $tabs as $callback => $text ) {
				$class = '';
				if ( $current == $callback )
				$class = " class='current'";
				$href = add_query_arg(array('tab'=>$callback, 's'=>false, 'paged'=>false, 'post_mime_type'=>false, 'm'=>false));
				$link = "<a href='" . clean_url($href) . "'$class>$text</a>";
				echo "\t<li id='" . wpformat::attribute_escape("tab-$callback") . "'>$link</li>\n";
			}
			echo "</ul>\n";
		}
	}

	function get_image_send_to_editor($id, $alt, $title, $align, $url='', $rel = false, $size='medium') {

		$html = wpadmin::get_image_tag($id, $alt, $title, $align, $size);

		$rel = $rel ? ' rel="attachment wp-att-'.wpformat::attribute_escape($id).'"' : '';

		if ( $url )
		$html = '<a href="' . wpcomment::clean_url($url) . "\"$rel>$html</a>";

		$html = wpbasic::apply_filters( 'image_send_to_editor', $html, $id, $alt, $title, $align, $url, $size );

		return $html;
	}

	function image_add_caption( $html, $id, $alt, $title, $align, $url, $size ) {

		if ( empty($alt) || wpbasic::apply_filters( 'disable_captions', '' ) ) return $html;
		$id = ( 0 < (int) $id ) ? 'attachment_' . $id : '';

		preg_match( '/width="([0-9]+)/', $html, $matches );
		if ( ! isset($matches[1]) ) return $html;
		$width = $matches[1];

		$html = preg_replace( '/align[^\s\'"]+\s?/', '', $html );
		if ( empty($align) ) $align = 'none';

		$shcode = '[caption id="' . $id . '" align="align' . $align
		. '" width="' . $width . '" caption="' . $alt . '"]' . $html . '[/caption]';

		return wpbasic::apply_filters( 'image_add_caption_shortcode', $shcode, $html );
	}

	//TODO: what is this?
	/*
	add_filter( 'image_send_to_editor', 'image_add_caption', 20, 7 );
	*/

	//TODO: clean this out; separate logic and output or encapsulate it/ echo it.
	function media_send_to_editor($html) {
		echo '<script type="text/javascript">'
			.'/* <![CDATA[ */'
			.'var win = window.dialogArguments || opener || parent || top;'
			."win.send_to_editor('"
			.addslashes($html) 
			."');"
			.'/* ]]> */'
			.'</script>';
		exit;
	}

	// this handles the file upload POST itself, creating the attachment post
	function media_handle_upload($file_id, $post_id, $post_data = array()) {
		$overrides = array('test_form'=>false);
		$file = wpadmin::wp_handle_upload($_FILES[$file_id], $overrides);

		if ( isset($file['error']) )
		return new WP_Error( 'upload_error', $file['error'] );

		$url = $file['url'];
		$type = $file['type'];
		$file = $file['file'];
		$title = preg_replace('/\.[^.]+$/', '', basename($file));
		$content = '';

		// use image exif/iptc data for title and caption defaults if possible
		if ( $image_meta = @ wpadmin::wp_read_image_metadata($file) ) {
			if ( trim($image_meta['title']) )
			$title = $image_meta['title'];
			if ( trim($image_meta['caption']) )
			$content = $image_meta['caption'];
		}

		// Construct the attachment array
		$attachment = array_merge( array(
		'post_mime_type' => $type,
		'guid' => $url,
		'post_parent' => $post_id,
		'post_title' => $title,
		'post_content' => $content,
		), $post_data );

		// Save the data
		$id = wppost::wp_insert_attachment($attachment, $file, $post_parent);
		if ( !is_wp_error($id) ) {
			wpadmin::wp_update_attachment_metadata( $id, wpadmin::wp_generate_attachment_metadata( $id, $file ) );
		}

		return $id;

	}

	function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) {
		$overrides = array('test_form'=>false);
		$file = wpadmin::wp_handle_sideload($file_array, $overrides);

		if ( isset($file['error']) )
		return new WP_Error( 'upload_error', $file['error'] );

		$url = $file['url'];
		$type = $file['type'];
		$file = $file['file'];
		$title = preg_replace('/\.[^.]+$/', '', basename($file));
		$content = '';

		// use image exif/iptc data for title and caption defaults if possible
		if ( $image_meta = @ wpadmin::wp_read_image_metadata($file) ) {
			if ( trim($image_meta['title']) )
			$title = $image_meta['title'];
			if ( trim($image_meta['caption']) )
			$content = $image_meta['caption'];
		}

		$title = @$desc;

		// Construct the attachment array
		$attachment = array_merge( array(
		'post_mime_type' => $type,
		'guid' => $url,
		'post_parent' => $post_id,
		'post_title' => $title,
		'post_content' => $content,
		), $post_data );

		// Save the data
		$id = wppost::wp_insert_attachment($attachment, $file, $post_parent);
		if ( !is_wp_error($id) ) {
			wpadmin::wp_update_attachment_metadata( $id, wpadmin::wp_generate_attachment_metadata( $id, $file ) );
			return $url;
		}
		return $id;
	}


	// wrap iframe content (produced by $content_func) in a doctype, html head/body etc
	// any additional function args will be passed to content_func
	function wp_iframe($content_func /* ... */) {
		?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
<?php wpbasic::do_action('admin_xml_ns'); ?>
<?php wptemplate::language_attributes(); ?>>
<head>
<meta http-equiv="Content-Type"
	content="<?php bloginfo('html_type'); ?>; charset=<?php echo wpbasic::get_option('blog_charset'); ?>" />
<title><?php bloginfo('name') ?> &rsaquo; <?php _e('Uploads'); ?>
&#8212; <?php _e('WordPress'); ?></title>
	<?php
	wp_enqueue_style( 'global' );
	wp_enqueue_style( 'wp-admin' );
	wp_enqueue_style( 'colors' );
	if ( 0 === strpos( $content_func, 'media' ) )
	wp_enqueue_style( 'media' );

	echo '<script type="text/javascript">'
	.'//<![CDATA['
	.'function addLoadEvent(func) {if ( typeof wpOnload != "function" ){wpOnload=func;}else{ var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}}"
	.'//]]>'
	.'</script>';
	wpbasic::do_action('admin_print_styles');
	wpbasic::do_action('admin_print_scripts');
	wpbasic::do_action('admin_head');
	if ( is_string($content_func) )
	wpbasic::do_action( "admin_head_{$content_func}" );
	?>
</head>
<body
<?php
//TODO: handle these globals! remove raw html
if ( isset($GLOBALS['body_id']) ) echo ' id="' . $GLOBALS['body_id'] . '"'; ?>>
<?php
$args = func_get_args();
$args = array_slice($args, 1);
call_user_func_array($content_func, $args);
?>
</body>
</html>
<?php
	}

	function media_buttons() {
		global $post_ID, $temp_ID;
		$uploading_iframe_ID = (int) (0 == $post_ID ? $temp_ID : $post_ID);
		$context = wpbasic::apply_filters('media_buttons_context', __('Add media: %s'));
		$media_upload_iframe_src = "media-upload.php?post_id=$uploading_iframe_ID";
		$media_title = __('Add Media');
		$image_upload_iframe_src = wpbasic::apply_filters('image_upload_iframe_src', "$media_upload_iframe_src&amp;type=image");
		$image_title = __('Add an Image');
		$video_upload_iframe_src = wpbasic::apply_filters('video_upload_iframe_src', "$media_upload_iframe_src&amp;type=video");
		$video_title = __('Add Video');
		$audio_upload_iframe_src = wpbasic::apply_filters('audio_upload_iframe_src', "$media_upload_iframe_src&amp;type=audio");
		$audio_title = __('Add Audio');
		$out = <<<EOF

		<a href="{$image_upload_iframe_src}&amp;TB_iframe=true" id="add_image" class="thickbox" title='$image_title'><img src='images/media-button-image.gif' alt='$image_title' /></a>
		<a href="{$video_upload_iframe_src}&amp;TB_iframe=true" id="add_video" class="thickbox" title='$video_title'><img src='images/media-button-video.gif' alt='$video_title' /></a>
		<a href="{$audio_upload_iframe_src}&amp;TB_iframe=true" id="add_audio" class="thickbox" title='$audio_title'><img src='images/media-button-music.gif' alt='$audio_title' /></a>
		<a href="{$media_upload_iframe_src}&amp;TB_iframe=true" id="add_media" class="thickbox" title='$media_title'><img src='images/media-button-other.gif' alt='$media_title' /></a>

EOF;
		printf($context, $out);
	}

	/*  //TODO: what is this?
	 add_action( 'media_buttons', 'media_buttons' );
	 add_action('media_upload_media', 'media_upload_handler');
	 */

	function media_upload_form_handler() {
		wpadmin::check_admin_referer('media-form');

		if ( !empty($_POST['attachments']) ) foreach ( $_POST['attachments'] as $attachment_id => $attachment ) {
			$post = $_post = wpbasic::get_post($attachment_id, ARRAY_A);
			if ( isset($attachment['post_content']) )
			$post['post_content'] = $attachment['post_content'];
			if ( isset($attachment['post_title']) )
			$post['post_title'] = $attachment['post_title'];
			if ( isset($attachment['post_excerpt']) )
			$post['post_excerpt'] = $attachment['post_excerpt'];
			if ( isset($attachment['menu_order']) )
			$post['menu_order'] = $attachment['menu_order'];

			$post = wpbasic::apply_filters('attachment_fields_to_save', $post, $attachment);

			if ( isset($post['errors']) ) {
				$errors[$attachment_id] = $post['errors'];
				unset($post['errors']);
			}

			if ( $post != $_post )
			wppost::wp_update_post($post);

			foreach ( get_attachment_taxonomies($post) as $t )
			if ( isset($attachment[$t]) )
			wpadmin::wp_set_object_terms($attachment_id, array_map('trim', preg_split('/,+/', $attachment[$t])), $t, false);
		}

		if ( isset($_POST['insert-gallery']) )
		return wpadmin::media_send_to_editor('[gallery]');

		if ( isset($_POST['send']) ) {
			$keys = array_keys($_POST['send']);
			$send_id = (int) array_shift($keys);
			$attachment = stripslashes_deep( $_POST['attachments'][$send_id] );
			$html = $attachment['post_title'];
			if ( !empty($attachment['url']) ) {
				if ( strpos($attachment['url'], 'attachment_id') || false !== strpos($attachment['url'], wplink::get_permalink($_POST['post_id'])) )
				$rel = " rel='attachment wp-att-".wpformat::attribute_escape($send_id)."'";
				$html = "<a href='{$attachment['url']}'$rel>$html</a>";
			}
			$html = wpbasic::apply_filters('media_send_to_editor', $html, $send_id, $attachment);
			return wpadmin::media_send_to_editor($html);
		}

		return $errors;
	}

	function media_upload_image() {
		if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
			// Upload File button was clicked
			$id = wpadmin::media_handle_upload('async-upload', $_REQUEST['post_id']);
			unset($_FILES);
			if ( WP_Error::is_wp_error($id) ) {
				$errors['upload_error'] = $id;
				$id = false;
			}
		}

		if ( !empty($_POST['insertonlybutton']) ) {
			$src = $_POST['insertonly']['src'];
			if ( !empty($src) && !strpos($src, '://') )
			$src = "http://$src";
			$alt = wpformat::attribute_escape($_POST['insertonly']['alt']);
			if ( isset($_POST['insertonly']['align']) ) {
				$align = wpformat::attribute_escape($_POST['insertonly']['align']);
				$class = " class='align$align'";
			}
			if ( !empty($src) )
			$html = "<img src='$src' alt='$alt'$class />";
			return wpadmin::media_send_to_editor($html);
		}

		if ( !empty($_POST) ) {
			$return = wpadmin::media_upload_form_handler();

			if ( is_string($return) )
			return $return;
			if ( is_array($return) )
			$errors = $return;
		}

		if ( isset($_POST['save']) ) {
			$errors['upload_notice'] = __('Saved.');
			return wpadmin::media_upload_gallery();
		}

		return wpadmin::wp_iframe( 'media_upload_type_form', 'image', $errors, $id );
	}

	function media_sideload_image($file, $post_id, $desc = null) {
		if (!empty($file) ) {
			$file_array['name'] = basename($file);
			$file_array['tmp_name'] = wpadmin::download_url($file);
			$desc = @$desc;

			$id = wpadmin::media_handle_sideload($file_array, $post_id, $desc);
			$src = $id;

			if ( WP_Error::is_wp_error($id) ) {
				@unlink($file_array['tmp_name']);
				return $id;
			}
		}

		if ( !empty($src) ) {
			$alt = @$desc;
			$html = "<img src='$src' alt='$alt' />";
			return $html;
		}
	}

	function media_upload_audio() {
		if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
			// Upload File button was clicked
			$id = wpadmin::media_handle_upload('async-upload', $_REQUEST['post_id']);
			unset($_FILES);
			if ( WP_Error::is_wp_error($id) ) {
				$errors['upload_error'] = $id;
				$id = false;
			}
		}

		if ( !empty($_POST['insertonlybutton']) ) {
			$href = $_POST['insertonly']['href'];
			if ( !empty($href) && !strpos($href, '://') )
			$href = "http://$href";
			$title = wpformat::attribute_escape($_POST['insertonly']['title']);
			if ( empty($title) )
			$title = basename($href);
			if ( !empty($title) && !empty($href) )
			$html = "<a href='$href' >$title</a>";
			return wpadmin::media_send_to_editor($html);
		}

		if ( !empty($_POST) ) {
			$return = wpadmin::media_upload_form_handler();

			if ( is_string($return) )
			return $return;
			if ( is_array($return) )
			$errors = $return;
		}

		if ( isset($_POST['save']) ) {
			$errors['upload_notice'] = __('Saved.');
			return wpadmin::media_upload_gallery();
		}

		return wpadmin::wp_iframe( 'media_upload_type_form', 'audio', $errors, $id );
	}

	function media_upload_video() {
		if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
			// Upload File button was clicked
			$id = wpadmin::media_handle_upload('async-upload', $_REQUEST['post_id']);
			unset($_FILES);
			if ( WP_Error::is_wp_error($id) ) {
				$errors['upload_error'] = $id;
				$id = false;
			}
		}

		if ( !empty($_POST['insertonlybutton']) ) {
			$href = $_POST['insertonly']['href'];
			if ( !empty($href) && !strpos($href, '://') )
			$href = "http://$href";
			$title = wpformat::attribute_escape($_POST['insertonly']['title']);
			if ( empty($title) )
			$title = basename($href);
			if ( !empty($title) && !empty($href) )
			$html = "<a href='$href' >$title</a>";
			return wpadmin::media_send_to_editor($html);
		}

		if ( !empty($_POST) ) {
			$return = wpadmin::media_upload_form_handler();

			if ( is_string($return) )
			return $return;
			if ( is_array($return) )
			$errors = $return;
		}

		if ( isset($_POST['save']) ) {
			$errors['upload_notice'] = __('Saved.');
			return wpadmin::media_upload_gallery();
		}

		return wp_iframe( 'media_upload_type_form', 'video', $errors, $id );
	}

	function media_upload_file() {
		if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
			// Upload File button was clicked
			$id = wpadmin::media_handle_upload('async-upload', $_REQUEST['post_id']);
			unset($_FILES);
			if ( WP_Error::is_wp_error($id) ) {
				$errors['upload_error'] = $id;
				$id = false;
			}
		}

		if ( !empty($_POST['insertonlybutton']) ) {
			$href = $_POST['insertonly']['href'];
			if ( !empty($href) && !strpos($href, '://') )
			$href = "http://$href";
			$title = wpformat::attribute_escape($_POST['insertonly']['title']);
			if ( empty($title) )
			$title = basename($href);
			if ( !empty($title) && !empty($href) )
			$html = "<a href='$href' >$title</a>";
			return wpadmin::media_send_to_editor($html);
		}

		if ( !empty($_POST) ) {
			$return = wpadmin::media_upload_form_handler();

			if ( is_string($return) )
			return $return;
			if ( is_array($return) )
			$errors = $return;
		}

		if ( isset($_POST['save']) ) {
			$errors['upload_notice'] = __('Saved.');
			return wpadmin::media_upload_gallery();
		}

		return wp_iframe( 'media_upload_type_form', 'file', $errors, $id );
	}

	function media_upload_gallery() {
		if ( !empty($_POST) ) {
			$return = wpadmin::media_upload_form_handler();

			if ( is_string($return) )
			return $return;
			if ( is_array($return) )
			$errors = $return;
		}

		WP_Scripts::wp_enqueue_script('admin-gallery');
		return wpadmin::wp_iframe( 'media_upload_gallery_form', $errors );
	}

	function media_upload_library() {
		if ( !empty($_POST) ) {
			$return = wpadmin::media_upload_form_handler();

			if ( is_string($return) )
			return $return;
			if ( is_array($return) )
			$errors = $return;
		}

		return wp_iframe( 'media_upload_library_form', $errors );
	}

	function image_attachment_fields_to_edit($form_fields, $post) {
		if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
			$form_fields['post_title']['required'] = true;

			$form_fields['post_excerpt']['label'] = __('Caption');
			$form_fields['post_excerpt']['helps'][] = __('Also used as alternate text for the image');

			$form_fields['post_content']['label'] = __('Description');

			$thumb = wppost::wp_get_attachment_thumb_url($post->ID);

			$form_fields['align'] = array(
			'label' => __('Alignment'),
			'input' => 'html',
			'html'  => "
			<input type='radio' name='attachments[$post->ID][align]' id='image-align-none-$post->ID' value='none' checked='checked' />
			<label for='image-align-none-$post->ID' class='align image-align-none-label'>" . __('None') . "</label>
			<input type='radio' name='attachments[$post->ID][align]' id='image-align-left-$post->ID' value='left' />
			<label for='image-align-left-$post->ID' class='align image-align-left-label'>" . __('Left') . "</label>
			<input type='radio' name='attachments[$post->ID][align]' id='image-align-center-$post->ID' value='center' />
			<label for='image-align-center-$post->ID' class='align image-align-center-label'>" . __('Center') . "</label>
			<input type='radio' name='attachments[$post->ID][align]' id='image-align-right-$post->ID' value='right' />
			<label for='image-align-right-$post->ID' class='align image-align-right-label'>" . __('Right') . "</label>\n",
			);
			$form_fields['image-size'] = array(
			'label' => __('Size'),
			'input' => 'html',
			'html'  => "
				" . ( $thumb ? "<input type='radio' name='attachments[$post->ID][image-size]' id='image-size-thumb-$post->ID' value='thumbnail' />
			<label for='image-size-thumb-$post->ID'>" . __('Thumbnail') . "</label>
				" : '' ) . "<input type='radio' name='attachments[$post->ID][image-size]' id='image-size-medium-$post->ID' value='medium' checked='checked' />
			<label for='image-size-medium-$post->ID'>" . __('Medium') . "</label>
			<input type='radio' name='attachments[$post->ID][image-size]' id='image-size-full-$post->ID' value='full' />
			<label for='image-size-full-$post->ID'>" . __('Full size') . "</label>",
			);
		}
		return $form_fields;
	}
	/* //TODO: what is this?
	 add_filter('attachment_fields_to_edit', 'image_attachment_fields_to_edit', 10, 2);
	 */
	function media_single_attachment_fields_to_edit( $form_fields, $post ) {
		unset($form_fields['url'], $form_fields['align'], $form_fields['image-size']);
		return $form_fields;
	}

	function image_attachment_fields_to_save($post, $attachment) {
		if ( substr($post['post_mime_type'], 0, 5) == 'image' ) {
			if ( strlen(trim($post['post_title'])) == 0 ) {
				$post['post_title'] = preg_replace('/\.\w+$/', '', basename($post['guid']));
				$post['errors']['post_title']['errors'][] = __('Empty Title filled from filename.');
			}
		}

		return $post;
	}
	/* //TODO: what is this?
	 add_filter('attachment_fields_to_save', 'image_attachment_fields_to_save', 10, 2);
	 */
	function image_media_send_to_editor($html, $attachment_id, $attachment) {
		$post =& get_post($attachment_id);
		if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
			$url = $attachment['url'];

			if ( isset($attachment['align']) )
			$align = $attachment['align'];
			else
			$align = 'none';

			if ( !empty($attachment['image-size']) )
			$size = $attachment['image-size'];
			else
			$size = 'medium';

			$rel = ( $url == wplink::get_attachment_link($attachment_id) );

			return wpadmin::get_image_send_to_editor($attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size);
		}

		return $html;
	}
	/* //TODO: what is this?
	 add_filter('media_send_to_editor', 'image_media_send_to_editor', 10, 3);
	 */
	function get_attachment_fields_to_edit($post, $errors = null) {
		if ( is_int($post) )
		$post =& get_post($post);
		if ( is_array($post) )
		$post = (object) $post;

		$edit_post = sanitize_post($post, 'edit');
		$file = wppost::wp_get_attachment_url($post->ID);
		$link = wplink::get_attachment_link($post->ID);

		$form_fields = array(
		'post_title'   => array(
			'label'      => __('Title'),
			'value'      => $edit_post->post_title,
		),
		'post_excerpt' => array(
			'label'      => __('Caption'),
			'value'      => $edit_post->post_excerpt,
		),
		'post_content' => array(
			'label'      => __('Description'),
			'value'      => $edit_post->post_content,
			'input'      => 'textarea',
		),
		'url'          => array(
			'label'      => __('Link URL'),
			'input'      => 'html',
			'html'       => "
		<input type='text' name='attachments[$post->ID][url]' value='" . wpformat::attribute_escape($file) . "' /><br />
		<button type='button' class='button url-$post->ID' title=''>" . __('None') . "</button>
		<button type='button' class='button url-$post->ID' title='" . wpformat::attribute_escape($file) . "'>" . __('File URL') . "</button>
		<button type='button' class='button url-$post->ID' title='" . wpformat::attribute_escape($link) . "'>" . __('Post URL') . "</button>
		<script type='text/javascript'>
		jQuery('button.url-$post->ID').bind('click', function(){jQuery(this).siblings('input').val(jQuery(this).attr('title'));});
		</script>\n",
			'helps'      => __('Enter a link URL or click above for presets.'),
		),
    	'menu_order'   => array(
			'label'      => __('Order'),
			'value'      => $edit_post->menu_order
		),
		);

		foreach ( wpadmin::get_attachment_taxonomies($post) as $taxonomy ) {
			$t = (array) wpadmin::get_taxonomy($taxonomy);
			if ( empty($t['label']) )
			$t['label'] = $taxonomy;
			if ( empty($t['args']) )
			$t['args'] = array();

			$terms = wpadmin::get_object_term_cache($post->ID, $taxonomy);
			if ( empty($terms) )
			$terms = wpadmin::wp_get_object_terms($post->ID, $taxonomy, $t['args']);

			$values = array();

			foreach ( $terms as $term )
			$values[] = $term->name;
			$t['value'] = join(', ', $values);

			$form_fields[$taxonomy] = $t;
		}

		// Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
		// The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing )
		$form_fields = array_merge_recursive($form_fields, (array) $errors);

		$form_fields = wpbasic::apply_filters('attachment_fields_to_edit', $form_fields, $post);

		return $form_fields;
	}

	//TODO: remove globals!
	function get_media_items( $post_id, $errors ) {
		if ( $post_id ) {
			$post = wppost::get_post($post_id);
			if ( $post && $post->post_type == 'attachment' )
			$attachments = array($post->ID => $post);
			else
			$attachments = wpbasic::get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC') );
		} else {
			if ( is_array($GLOBALS['wp_the_query']->posts) )
			foreach ( $GLOBALS['wp_the_query']->posts as $attachment )
			$attachments[$attachment->ID] = $attachment;
		}

		if ( empty($attachments) )
		return '';

		foreach ( $attachments as $id => $attachment )
		if ( $item = wpadmin::get_media_item( $id, array( 'errors' => isset($errors[$id]) ? $errors[$id] : null) ) )
		$output .= "\n<div id='media-item-$id' class='media-item child-of-$attachment->post_parent preloaded'><div class='progress'><div class='bar'></div></div><div id='media-upload-error-$id'></div><div class='filename'></div>$item\n</div>";

		return $output;
	}

	function get_media_item( $attachment_id, $args = null ) {
		global $redir_tab;

		$default_args = array( 'errors' => null, 'send' => true, 'delete' => true, 'toggle' => true );
		$args = wpbasic::wp_parse_args( $args, $default_args );
		extract( $args, EXTR_SKIP );

		global $post_mime_types;
		if ( ( $attachment_id = intval($attachment_id) ) && $thumb_url = wptemplate::get_attachment_icon_src( $attachment_id ) )
		$thumb_url = $thumb_url[0];
		else
		return false;

		$title_label = __('Title');
		$description_label = __('Description');
		$tags_label = __('Tags');

		$toggle_on = __('Show');
		$toggle_off = __('Hide');

		$post = wppost::get_post($attachment_id);

		$filename = basename($post->guid);
		$title = wpformat::attribute_escape($post->post_title);
		$description = wpformat::attribute_escape($post->post_content);
		if ( $_tags = wptemplate::get_the_tags($attachment_id) ) {
			foreach ( $_tags as $tag )
			$tags[] = $tag->name;
			$tags = wpformat::attribute_escape(join(', ', $tags));
		}

		if ( isset($post_mime_types) ) {
			$keys = array_keys(wppost::wp_match_mime_types(array_keys($post_mime_types), $post->post_mime_type));
			$type = array_shift($keys);
			$type = "<input type='hidden' id='type-of-$attachment_id' value='" . wpformat::attribute_escape( $type ) . "' />";
		}

		$form_fields = wpadmin::get_attachment_fields_to_edit($post, $errors);

		if ( $toggle ) {
			$class = empty($errors) ? 'startclosed' : 'startopen';
			$toggle_links = "
			<a class='toggle describe-toggle-on' href='#'>$toggle_on</a>
			<a class='toggle describe-toggle-off' href='#'>$toggle_off</a>";
		} else {
			$class = 'form-table';
			$toggle_links = '';
		}

		$display_title = ( !empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case
		$display_title = wpformat::wp_html_excerpt($display_title, 60);

		$gallery = ( (isset($_REQUEST['tab']) && 'gallery' == $_REQUEST['tab']) || (isset($redir_tab) && 'gallery' == $redir_tab) ) ? true : false;
		$order = '';

		foreach ( $form_fields as $key => $val ) {
			if ( 'menu_order' == $key ) {
				if ( $gallery )
				$order = '<div class="menu_order"> <input class="menu_order_input" type="text" id="attachments['.$attachment_id.'][menu_order]" name="attachments['.$attachment_id.'][menu_order]" value="'.$val['value'].'" /></div>';
				else
				$order = '<input type="hidden" name="attachments['.$attachment_id.'][menu_order]" value="'.$val['value'].'" />';

				unset($form_fields['menu_order']);
				break;
			}
		}

		$item = "
		$type
		$toggle_links
		$order
		<div class='filename new'>$display_title</div>
		<table class='slidetoggle describe $class'>
		<thead class='media-item-info'>
		<tr>
		<td class='A1B1' rowspan='4'><img class='thumbnail' src='$thumb_url' alt='' /></td>
		<td>$filename</td>
		</tr>
		<tr><td>$post->post_mime_type</td></tr>
		<tr><td>" . wpbasic::mysql2date($post->post_date, wpbasic::get_option('time_format')) . "</td></tr>
		<tr><td>" . wpbasic::apply_filters('media_meta', '', $post) . "</td></tr>
		</thead>
		<tbody>\n";

		$defaults = array(
		'input'      => 'text',
		'required'   => false,
		'value'      => '',
		'extra_rows' => array(),
		);

		$delete_href = wpbasic::wp_nonce_url("post.php?action=delete-post&amp;post=$attachment_id", 'delete-post_' . $attachment_id);
		if ( $send )
		$send = "<input type='submit' class='button' name='send[$attachment_id]' value='" . attribute_escape( __( 'Insert into Post' ) ) . "' />";
		if ( $delete )
		$delete = "<a href=\"#\" class=\"del-link\" onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\">" . __('Delete') . "</a>";
		if ( ( $send || $delete ) && !isset($form_fields['buttons']) )
		$form_fields['buttons'] = array('tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send $delete
		<div id=\"del_attachment_$attachment_id\" class=\"del-attachment\" style=\"display:none;\">" . sprintf(__("You are about to delete <strong>%s</strong>."), $filename) . " <a href=\"$delete_href\" id=\"del[$attachment_id]\" class=\"delete\">" . __('Continue') . "</a>
		<a href=\"#\" class=\"del-link\" onclick=\"this.parentNode.style.display='none';return false;\">" . __('Cancel') . "</a></div></td></tr>\n");

		$hidden_fields = array();

		foreach ( $form_fields as $id => $field ) {
			if ( $id{0} == '_' )
			continue;

			if ( !empty($field['tr']) ) {
				$item .= $field['tr'];
				continue;
			}

			$field = array_merge($defaults, $field);
			$name = "attachments[$attachment_id][$id]";

			if ( $field['input'] == 'hidden' ) {
				$hidden_fields[$name] = $field['value'];
				continue;
			}

			$required = $field['required'] ? '<abbr title="required" class="required">*</abbr>' : '';
			$aria_required = $field['required'] ? " aria-required='true' " : '';
			$class  = $id;
			$class .= $field['required'] ? ' form-required' : '';

			$item .= "\t\t<tr class='$class'>\n\t\t\t<th valign='top' scope='row' class='label'><label for='$name'><span class='alignleft'>{$field['label']}</span><span class='alignright'>$required</span><br class='clear' /></label></th>\n\t\t\t<td class='field'>";
			if ( !empty($field[$field['input']]) )
			$item .= $field[$field['input']];
			elseif ( $field['input'] == 'textarea' ) {
				$item .= "<textarea type='text' id='$name' name='$name'" . $aria_required . ">" . htmlspecialchars( $field['value'] ) . "</textarea>";
			} else {
				$item .= "<input type='text' id='$name' name='$name' value='" . wpformat::attribute_escape( $field['value'] ) . "'" . $aria_required . "/>";
			}
			if ( !empty($field['helps']) )
			$item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique((array) $field['helps']) ) . '</p>';
			$item .= "</td>\n\t\t</tr>\n";

			$extra_rows = array();

			if ( !empty($field['errors']) )
			foreach ( array_unique((array) $field['errors']) as $error )
			$extra_rows['error'][] = $error;

			if ( !empty($field['extra_rows']) )
			foreach ( $field['extra_rows'] as $class => $rows )
			foreach ( (array) $rows as $html )
			$extra_rows[$class][] = $html;

			foreach ( $extra_rows as $class => $rows )
			foreach ( $rows as $html )
			$item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
		}

		if ( !empty($form_fields['_final']) )
		$item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
		$item .= "\t</tbody>\n";
		$item .= "\t</table>\n";

		foreach ( $hidden_fields as $name => $value )
		$item .= "\t<input type='hidden' name='$name' id='$name' value='" . attribute_escape( $value ) . "' />\n";

		return $item;
	}

	function media_upload_header() {
		?>
<script type="text/javascript">post_id = <?php echo intval($_REQUEST['post_id']); ?>;</script>
<div id="media-upload-header"><?php wpadmin::the_media_upload_tabs(); ?></div>
		<?php
	}

	//TODO: fix global reference
	function media_upload_form( $errors = null ) {
		global $type, $tab;

		$flash_action_url = wptemplate::admin_url('async-upload.php');

		// If Mac and mod_security, no Flash. :(
		$flash = true;
		if ( false !== strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'mac') && apache_mod_loaded('mod_security') )
		$flash = false;

		$flash = wpbasic::apply_filters('flash_uploader', $flash);
		$post_id = intval($_REQUEST['post_id']);

		?>
<div id="media-upload-notice"><?php if (isset($errors['upload_notice']) ) { ?>
<?php echo $errors['upload_notice']; ?> <?php } ?></div>
<div id="media-upload-error"><?php if (isset($errors['upload_error']) && WP_Error::is_wp_error($errors['upload_error'])) { ?>
<?php echo $errors['upload_error']->get_error_message(); ?> <?php } ?></div>

<?php wpbasic::do_action('pre-upload-ui'); ?>

<?php
//TODO:  remove/refactor this
if ( $flash ) : ?>
<script type="text/javascript">
<!--
jQuery(function($){
	swfu = new SWFUpload({
			upload_url : "<?php echo attribute_escape( $flash_action_url ); ?>",
			flash_url : "<?php echo includes_url('js/swfupload/swfupload_f9.swf'); ?>",
			file_post_name: "async-upload",
			file_types: "<?php echo wpbasic::apply_filters('upload_file_glob', '*.*'); ?>",
			post_params : {
				"post_id" : "<?php echo $post_id; ?>",
				"auth_cookie" : "<?php if ( is_ssl() ) echo $_COOKIE[SECURE_AUTH_COOKIE]; else echo $_COOKIE[AUTH_COOKIE]; ?>",
				"_wpnonce" : "<?php echo wp_create_nonce('media-form'); ?>",
				"type" : "<?php echo $type; ?>",
				"tab" : "<?php echo $tab; ?>",
				"short" : "1"
			},
			file_size_limit : "<?php echo wp_max_upload_size(); ?>b",
			swfupload_element_id : "flash-upload-ui", // id of the element displayed when swfupload is available
			degraded_element_id : "html-upload-ui",   // when swfupload is unavailable
			file_dialog_start_handler : fileDialogStart,
			file_queued_handler : fileQueued,
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,

			debug: false
		});
	$("#flash-browse-button").bind( "click", function(){swfu.selectFiles();});
});
//-->
</script>

<div id="flash-upload-ui"><?php wpbasic::do_action('pre-flash-upload-ui'); ?>
<p><input id="flash-browse-button" type="button"
	value="<?php echo wpformat::attribute_escape( __( 'Choose files to upload' ) ); ?>"
	class="button" /></p>
<?php wpbasic::do_action('post-flash-upload-ui'); ?>
<p class="howto"><?php _e('After a file has been uploaded, you can add titles and descriptions.'); ?></p>
</div>

<?php endif; // $flash ?>

<div id="html-upload-ui"><?php wpbasic::do_action('pre-html-upload-ui'); ?>
<p><input type="file" name="async-upload" id="async-upload" /> <input
	type="submit" class="button" name="html-upload"
	value="<?php echo wpformat::attribute_escape(__('Upload')); ?>" /> <a
	href="#" onclick="return top.tb_remove();"><?php _e('Cancel'); ?></a></p>
<br class="clear" />
<?php if ( is_lighttpd_before_150() ): ?>
<p><?php _e('If you want to use all capabilities of the uploader, like uploading multiple files at once, please upgrade to lighttpd 1.5.'); ?></p>
<?php endif;?> <?php wpbasic::do_action('post-html-upload-ui'); ?></div>
<?php wpbasic::do_action('post-upload-ui'); ?>
<?php
	}

	function media_upload_type_form($type = 'file', $errors = null, $id = null) {
		wpadmin::media_upload_header();

		$post_id = intval($_REQUEST['post_id']);

		$form_action_url = wptemplate::admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id");
		$form_action_url = wpbasic::apply_filters('media_upload_form_url', $form_action_url, $type);

		$callback = "type_form_$type";
		?>

<form enctype="multipart/form-data" method="post"
	action="<?php echo attribute_escape($form_action_url); ?>"
	class="media-upload-form type-form validate"
	id="<?php echo $type; ?>-form"><input type="hidden" name="post_id"
	id="post_id" value="<?php echo (int) $post_id; ?>" /> <?php wpbasic::wp_nonce_field('media-form'); ?>
<h3><?php _e('From Computer'); ?></h3>
		<?php wpadmin::media_upload_form( $errors ); ?> <script
	type="text/javascript">
<!--
jQuery(function($){
	var preloaded = $(".media-item.preloaded");
	if ( preloaded.length > 0 ) {
		preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
	}
	updateMediaForm();
});
-->
</script> <?php if ( $id && !is_wp_error($id) ) : ?>
<div id="media-items"><?php echo get_media_items( $id, $errors ); ?></div>
<input type="submit" class="button savebutton" name="save"
	value="<?php echo wpformat::attribute_escape( __( 'Save all changes' ) ); ?>" />

		<?php elseif ( is_callable($callback) ) : ?>

<div class="media-blank">
<p style="text-align: center"><?php _e('&mdash; OR &mdash;'); ?></p>
<h3><?php _e('From URL'); ?></h3>
</div>

<script type="text/javascript">
//<![CDATA[
var addExtImage = {

	width : '',
	height : '',
	align : 'alignnone',

	insert : function() {
		var t = this, html, f = document.forms[0], cls, title = '', alt = '', caption = null;

		if ( '' == f.src.value || '' == t.width ) return false;

		if ( f.title.value ) {
			title = f.title.value.replace(/['"<>]+/g, '');
			title = ' title="'+title+'"';
		}

		if ( f.alt.value ) {
			alt = f.alt.value.replace(/['"<>]+/g, '');
<?php if ( ! wpbasic::apply_filters( 'disable_captions', '' ) ) { ?>
			caption = f.alt.value.replace(/'/g, '&#39;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
<?php } ?>
		}

		cls = caption ? '' : ' class="'+t.align+'"';

		html = '<img alt="'+alt+'" src="'+f.src.value+'"'+title+cls+' width="'+t.width+'" height="'+t.height+'" />';

		if ( f.url.value )
			html = '<a href="'+f.url.value+'">'+html+'</a>';

		if ( caption )
			html = '[caption id="" align="'+t.align+'" width="'+t.width+'" caption="'+caption+'"]'+html+'[/caption]';

		var win = window.dialogArguments || opener || parent || top;
		win.send_to_editor(html);
	},

	resetImageData : function() {
		var t = addExtImage;

		t.width = t.height = '';
		document.getElementById('go_button').style.color = '#bbb';
		if ( ! document.forms[0].src.value )
			document.getElementById('status_img').src = 'images/required.gif';
		else document.getElementById('status_img').src = 'images/no.png';
	},

	updateImageData : function() {
		var t = addExtImage;

		t.width = t.preloadImg.width;
		t.height = t.preloadImg.height;
		document.getElementById('go_button').style.color = '#333';
		document.getElementById('status_img').src = 'images/yes.png';
	},

	getImageData : function() {
		var t = addExtImage, src = document.forms[0].src.value;

		if ( ! src ) {
			t.resetImageData();
			return false;
		}
		document.getElementById('status_img').src = 'images/loading.gif';
		t.preloadImg = new Image();
		t.preloadImg.onload = t.updateImageData;
		t.preloadImg.onerror = t.resetImageData;
		t.preloadImg.src = src;
	}
}
//]]>
</script>

<div id="media-items">
<div class="media-item media-blank"><?php echo call_user_func($callback); ?>
</div>
</div>
<input type="submit" class="button savebutton" name="save"
	value="<?php echo attribute_escape( __( 'Save all changes' ) ); ?>" />
</form>
<?php
endif;
	}

	function media_upload_gallery_form($errors) {
		global $redir_tab;

		$redir_tab = 'gallery';
		media_upload_header();

		$post_id = intval($_REQUEST['post_id']);
		$form_action_url = admin_url("media-upload.php?type={$GLOBALS['type']}&tab=gallery&post_id=$post_id");
		?>

<script type="text/javascript">
<!--
jQuery(function($){
	var preloaded = $(".media-item.preloaded");
	if ( preloaded.length > 0 ) {
		preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
		updateMediaForm();
	}
});
-->
</script>

<form enctype="multipart/form-data" method="post"
	action="<?php echo attribute_escape($form_action_url); ?>"
	class="media-upload-form validate" id="gallery-form"><?php wp_nonce_field('media-form'); ?>
		<?php //media_upload_form( $errors ); ?>
<table class="widefat">
	<thead>
		<tr>
			<th><?php _e('Media'); ?></th>
			<th class="order-head"><?php _e('Order'); ?></th>
		</tr>
	</thead>
</table>
<div id="media-items"><?php echo get_media_items($post_id, $errors); ?>
</div>
<p class="ml-submit"><input type="submit" class="button savebutton"
	name="save"
	value="<?php echo attribute_escape( __( 'Save all changes' ) ); ?>" />
<input type="submit" class="button insert-gallery" name="insert-gallery"
	value="<?php echo attribute_escape( __( 'Insert gallery into post' ) ); ?>" />
<input type="hidden" name="post_id" id="post_id"
	value="<?php echo (int) $post_id; ?>" /> <input type="hidden"
	name="type" value="<?php echo attribute_escape( $GLOBALS['type'] ); ?>" />
<input type="hidden" name="tab"
	value="<?php echo attribute_escape( $GLOBALS['tab'] ); ?>" /></p>
</form>
		<?php
	}

	function media_upload_library_form($errors) {
		global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types;

		media_upload_header();

		$post_id = intval($_REQUEST['post_id']);

		$form_action_url = admin_url("media-upload.php?type={$GLOBALS['type']}&tab=library&post_id=$post_id");

		$_GET['paged'] = intval($_GET['paged']);
		if ( $_GET['paged'] < 1 )
		$_GET['paged'] = 1;
		$start = ( $_GET['paged'] - 1 ) * 10;
		if ( $start < 1 )
		$start = 0;
		add_filter( 'post_limits', $limit_filter = create_function( '$a', "return 'LIMIT $start, 10';" ) );

		list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();

		?>

<form id="filter" action="" method="get"><input type="hidden"
	name="type" value="<?php echo attribute_escape( $type ); ?>" /> <input
	type="hidden" name="tab"
	value="<?php echo attribute_escape( $tab ); ?>" /> <input type="hidden"
	name="post_id" value="<?php echo (int) $post_id; ?>" /> <input
	type="hidden" name="post_mime_type"
	value="<?php echo attribute_escape( $_GET['post_mime_type'] ); ?>" />

<div id="search-filter"><label class="hidden" for="post-search-input"><?php _e('Search Media');?>:</label>
<input type="text" id="post-search-input" name="s"
	value="<?php the_search_query(); ?>" /> <input type="submit"
	value="<?php echo attribute_escape( __( 'Search Media' ) ); ?>"
	class="button" /></div>

<ul class="subsubsub">
<?php
$type_links = array();
$_num_posts = (array) wp_count_attachments();
$matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
foreach ( $matches as $_type => $reals )
foreach ( $reals as $real )
$num_posts[$_type] += $_num_posts[$real];
// If available type specified by media button clicked, filter by that type
if ( empty($_GET['post_mime_type']) && !empty($num_posts[$type]) ) {
	$_GET['post_mime_type'] = $type;
	list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
}
if ( empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all' )
$class = ' class="current"';
$type_links[] = "<li><a href='" . clean_url(add_query_arg(array('post_mime_type'=>'all', 'paged'=>false, 'm'=>false))) . "'$class>".__('All Types')."</a>";
foreach ( $post_mime_types as $mime_type => $label ) {
	$class = '';

	if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
	continue;

	if ( wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
	$class = ' class="current"';

	$type_links[] = "<li><a href='" . clean_url(add_query_arg(array('post_mime_type'=>$mime_type, 'paged'=>false))) . "'$class>" . sprintf(__ngettext($label[2][0], $label[2][1], $num_posts[$mime_type]), "<span id='$mime_type-counter'>" . number_format_i18n( $num_posts[$mime_type] ) . '</span>') . '</a>';
}
echo implode(' | </li>', $type_links) . '</li>';
unset($type_links);
?>
</ul>

<div class="tablenav"><?php
$page_links = paginate_links( array(
	'base' => add_query_arg( 'paged', '%#%' ),
	'format' => '',
	'total' => ceil($wp_query->found_posts / 10),
	'current' => $_GET['paged']
));

if ( $page_links )
echo "<div class='tablenav-pages'>$page_links</div>";
?>

<div class="alignleft"><?php

$arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM $wpdb->posts WHERE post_type = 'attachment' ORDER BY post_date DESC";

$arc_result = $wpdb->get_results( $arc_query );

$month_count = count($arc_result);

if ( $month_count && !( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) { ?>
<select name='m'>
	<option <?php selected( @$_GET['m'], 0 ); ?> value='0'><?php _e('Show all dates'); ?></option>
	<?php
	foreach ($arc_result as $arc_row) {
		if ( $arc_row->yyear == 0 )
		continue;
		$arc_row->mmonth = zeroise( $arc_row->mmonth, 2 );

		if ( $arc_row->yyear . $arc_row->mmonth == $_GET['m'] )
		$default = ' selected="selected"';
		else
		$default = '';

		echo "<option$default value='" . attribute_escape( $arc_row->yyear . $arc_row->mmonth ) . "'>";
		echo wp_specialchars( $wp_locale->get_month($arc_row->mmonth) . " $arc_row->yyear" );
		echo "</option>\n";
	}
	?>
</select> <?php } ?> <input type="submit" id="post-query-submit"
	value="<?php echo attribute_escape( __( 'Filter &#187;' ) ); ?>"
	class="button-secondary" /></div>

<br class="clear" />
</div>
</form>

<form enctype="multipart/form-data" method="post"
	action="<?php echo attribute_escape($form_action_url); ?>"
	class="media-upload-form validate" id="library-form"><?php wp_nonce_field('media-form'); ?>
	<?php //media_upload_form( $errors ); ?> <script type="text/javascript">
<!--
jQuery(function($){
	var preloaded = $(".media-item.preloaded");
	if ( preloaded.length > 0 ) {
		preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
		updateMediaForm();
	}
});
-->
</script>

<div id="media-items"><?php echo get_media_items(null, $errors); ?></div>
<p class="ml-submit"><input type="submit" class="button savebutton"
	name="save"
	value="<?php echo attribute_escape( __( 'Save all changes' ) ); ?>" />
<input type="hidden" name="post_id" id="post_id"
	value="<?php echo (int) $post_id; ?>" /></p>
</form>
	<?php
	}

	function type_form_image() {

		if ( wpbasic::apply_filters( 'disable_captions', '' ) ) {
			$alt = __('Alternate Text');
			$alt_help = __('Alt text for the image, e.g. "The Mona Lisa"');
		} else {
			$alt = __('Image Caption');
			$alt_help = __('Also used as alternate text for the image');
		}

		return '
	<table class="describe"><tbody>
		<tr>
			<th valign="top" scope="row" class="label" style="width:120px;">
				<span class="alignleft"><label for="src">' . __('Source') . '</label></span>
				<span class="alignright"><img id="status_img" src="images/required.gif" title="required" alt="required" /></span>
			</th>
			<td class="field"><input id="src" name="src" value="" type="text" aria-required="true" onblur="addExtImage.getImageData()" /></td>
		</tr>

		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="title">' . __('Image Title') . '</label></span>
				<span class="alignright"><abbr title="required" class="required">*</abbr></span>
			</th>
			<td class="field"><p><input id="title" name="title" value="" type="text" aria-required="true" /></p></td>
		</tr>

		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="alt">' . $alt . '</label></span>
			</th>
			<td class="field"><input id="alt" name="alt" value="" type="text" aria-required="true" />
			<p class="help">' . $alt_help . '</p></td>
		</tr>

		<tr class="align">
			<th valign="top" scope="row" class="label"><p><label for="align">' . __('Alignment') . '</label></p></th>
			<td class="field">
				<input name="align" id="align-none" value="alignnone" onclick="addExtImage.align=this.value" type="radio" checked="checked" />
				<label for="align-none" class="align image-align-none-label">' . __('None') . '</label>
				<input name="align" id="align-left" value="alignleft" onclick="addExtImage.align=this.value" type="radio" />
				<label for="align-left" class="align image-align-left-label">' . __('Left') . '</label>
				<input name="align" id="align-center" value="aligncenter" onclick="addExtImage.align=this.value" type="radio" />
				<label for="align-center" class="align image-align-center-label">' . __('Center') . '</label>
				<input name="align" id="align-right" value="alignright" onclick="addExtImage.align=this.value" type="radio" />
				<label for="align-right" class="align image-align-right-label">' . __('Right') . '</label>
			</td>
		</tr>

		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="url">' . __('Link URL') . '</label></span>
			</th>
			<td class="field"><input id="url" name="url" value="" type="text" /><br />

			<button type="button" class="button" value="" onclick="document.forms[0].url.value=null">' . __('None') . '</button>
			<button type="button" class="button" value="" onclick="document.forms[0].url.value=document.forms[0].src.value">' . __('Link to image') . '</button>
			<p class="help">' . __('Enter a link URL or click above for presets.') . '</p></td>
		</tr>

		<tr>
			<td></td>
			<td>
				<input type="button" class="button" id="go_button" style="color:#bbb;" onclick="addExtImage.insert()" value="' . attribute_escape(__('Insert into Post')) . '" />
			</td>
		</tr>
	</tbody></table>
';

	}

	function type_form_audio() {
		return '
	<table class="describe"><tbody>
		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="insertonly[href]">' . __('Audio File URL') . '</label></span>
				<span class="alignright"><abbr title="required" class="required">*</abbr></span>
			</th>
			<td class="field"><input id="insertonly[href]" name="insertonly[href]" value="" type="text" aria-required="true"></td>
		</tr>
		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="insertonly[title]">' . __('Title') . '</label></span>
				<span class="alignright"><abbr title="required" class="required">*</abbr></span>
			</th>
			<td class="field"><input id="insertonly[title]" name="insertonly[title]" value="" type="text" aria-required="true"></td>
		</tr>
		<tr><td></td><td class="help">' . __('Link text, e.g. "Still Alive by Jonathan Coulton"') . '</td></tr>
		<tr>
			<td></td>
			<td>
				<input type="submit" class="button" name="insertonlybutton" value="' . attribute_escape(__('Insert into Post')) . '" />
			</td>
		</tr>
	</tbody></table>
';
	}

	function type_form_video() {
		return '
	<table class="describe"><tbody>
		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="insertonly[href]">' . __('Video URL') . '</label></span>
				<span class="alignright"><abbr title="required" class="required">*</abbr></span>
			</th>
			<td class="field"><input id="insertonly[href]" name="insertonly[href]" value="" type="text" aria-required="true"></td>
		</tr>
		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="insertonly[title]">' . __('Title') . '</label></span>
				<span class="alignright"><abbr title="required" class="required">*</abbr></span>
			</th>
			<td class="field"><input id="insertonly[title]" name="insertonly[title]" value="" type="text" aria-required="true"></td>
		</tr>
		<tr><td></td><td class="help">' . __('Link text, e.g. "Lucy on YouTube"') . '</td></tr>
		<tr>
			<td></td>
			<td>
				<input type="submit" class="button" name="insertonlybutton" value="' . attribute_escape(__('Insert into Post')) . '" />
			</td>
		</tr>
	</tbody></table>
';
	}

	function type_form_file() {
		return '
	<table class="describe"><tbody>
		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="insertonly[href]">' . __('URL') . '</label></span>
				<span class="alignright"><abbr title="required" class="required">*</abbr></span>
			</th>
			<td class="field"><input id="insertonly[href]" name="insertonly[href]" value="" type="text" aria-required="true"></td>
		</tr>
		<tr>
			<th valign="top" scope="row" class="label">
				<span class="alignleft"><label for="insertonly[title]">' . __('Title') . '</label></span>
				<span class="alignright"><abbr title="required" class="required">*</abbr></span>
			</th>
			<td class="field"><input id="insertonly[title]" name="insertonly[title]" value="" type="text" aria-required="true"></td>
		</tr>
		<tr><td></td><td class="help">' . __('Link text, e.g. "Ransom Demands (PDF)"') . '</td></tr>
		<tr>
			<td></td>
			<td>
				<input type="submit" class="button" name="insertonlybutton" value="' . attribute_escape(__('Insert into Post')) . '" />
			</td>
		</tr>
	</tbody></table>
';
	}

	// support a GET parameter for disabling the flash uploader
	function media_upload_use_flash($flash) {
		if ( array_key_exists('flash', $_REQUEST) )
		$flash = !empty($_REQUEST['flash']);
		return $flash;
	}
	/* //TODO: what is this?
	 add_filter('flash_uploader', 'media_upload_use_flash');
	 */
	function media_upload_flash_bypass() {
		echo '<p class="upload-flash-bypass">';
		printf( __('You are using the Flash uploader.  Problems?  Try the <a href="%s">Browser uploader</a> instead.'), clean_url(add_query_arg('flash', 0)) );
		echo '</p>';
	}
	/* //TODO: what is this?
	 add_action('post-flash-upload-ui', 'media_upload_flash_bypass');
	 */
	function media_upload_html_bypass() {
		echo '<p class="upload-html-bypass">';
		if ( array_key_exists('flash', $_REQUEST) )
		// the user manually selected the browser uploader, so let them switch back to Flash
		printf( __('You are using the Browser uploader.  Try the <a href="%s">Flash uploader</a> instead.'), clean_url(add_query_arg('flash', 1)) );
		else
		// the user probably doesn't have Flash
		printf( __('You are using the Browser uploader.') );

		echo '</p>';
	}
	/* //TODO: what is this?
	 add_action('post-flash-upload-ui', 'media_upload_flash_bypass');
	 add_action('post-html-upload-ui', 'media_upload_html_bypass');
	 */
	// make sure the GET parameter sticks when we submit a form
	function media_upload_bypass_url($url) {
		if ( array_key_exists('flash', $_REQUEST) )
		$url = add_query_arg('flash', intval($_REQUEST['flash']));
		return $url;
	}
	/* //TODO: what is this?
	 add_filter('media_upload_form_url', 'media_upload_bypass_url');



	 add_filter('async_upload_image', 'get_media_item', 10, 2);
	 add_filter('async_upload_audio', 'get_media_item', 10, 2);
	 add_filter('async_upload_video', 'get_media_item', 10, 2);
	 add_filter('async_upload_file', 'get_media_item', 10, 2);

	 add_action('media_upload_image', 'media_upload_image');
	 add_action('media_upload_audio', 'media_upload_audio');
	 add_action('media_upload_video', 'media_upload_video');
	 add_action('media_upload_file', 'media_upload_file');

	 add_filter('media_upload_gallery', 'media_upload_gallery');

	 add_filter('media_upload_library', 'media_upload_library');
	 */
	///////////////  import.php  //////////////


	function get_importers() {
		global $wp_importers;
		if ( is_array($wp_importers) )
		uasort($wp_importers, create_function('$a, $b', 'return strcmp($a[0], $b[0]);'));
		return $wp_importers;
	}

	function register_importer( $id, $name, $description, $callback ) {
		global $wp_importers;
		if ( is_wp_error( $callback ) )
		return $callback;
		$wp_importers[$id] = array ( $name, $description, $callback );
	}

	function wp_import_cleanup( $id ) {
		wp_delete_attachment( $id );
	}

	function wp_import_handle_upload() {
		$overrides = array( 'test_form' => false, 'test_type' => false );
		$_FILES['import']['name'] .= '.import';
		$file = wp_handle_upload( $_FILES['import'], $overrides );

		if ( isset( $file['error'] ) )
		return $file;

		$url = $file['url'];
		$type = $file['type'];
		$file = addslashes( $file['file'] );
		$filename = basename( $file );

		// Construct the object array
		$object = array( 'post_title' => $filename,
		'post_content' => $url,
		'post_mime_type' => $type,
		'guid' => $url
		);

		// Save the data
		$id = wppost::wp_insert_attachment( $object, $file );

		return array( 'file' => $file, 'id' => $id );
	}

	////////////////  misc.php  //////////////


	function got_mod_rewrite() {
		$got_rewrite = apache_mod_loaded('mod_rewrite', true);
		return wpbasic::apply_filters('got_rewrite', $got_rewrite);
	}

	// Returns an array of strings from a file (.htaccess ) from between BEGIN
	// and END markers.
	function extract_from_markers( $filename, $marker ) {
		$result = array ();

		if (!file_exists( $filename ) ) {
			return $result;
		}

		if ( $markerdata = explode( "\n", implode( '', file( $filename ) ) ));
		{
			$state = false;
			foreach ( $markerdata as $markerline ) {
				if (strpos($markerline, '# END ' . $marker) !== false)
				$state = false;
				if ( $state )
				$result[] = $markerline;
				if (strpos($markerline, '# BEGIN ' . $marker) !== false)
				$state = true;
			}
		}

		return $result;
	}

	// Inserts an array of strings into a file (.htaccess ), placing it between
	// BEGIN and END markers.  Replaces existing marked info.  Retains surrounding
	// data.  Creates file if none exists.
	// Returns true on write success, false on failure.
	function insert_with_markers( $filename, $marker, $insertion ) {
		if (!file_exists( $filename ) || is_writeable( $filename ) ) {
			if (!file_exists( $filename ) ) {
				$markerdata = '';
			} else {
				$markerdata = explode( "\n", implode( '', file( $filename ) ) );
			}

			$f = fopen( $filename, 'w' );
			$foundit = false;
			if ( $markerdata ) {
				$state = true;
				foreach ( $markerdata as $n => $markerline ) {
					if (strpos($markerline, '# BEGIN ' . $marker) !== false)
					$state = false;
					if ( $state ) {
						if ( $n + 1 < count( $markerdata ) )
						fwrite( $f, "{$markerline}\n" );
						else
						fwrite( $f, "{$markerline}" );
					}
					if (strpos($markerline, '# END ' . $marker) !== false) {
						fwrite( $f, "# BEGIN {$marker}\n" );
						if ( is_array( $insertion ))
						foreach ( $insertion as $insertline )
						fwrite( $f, "{$insertline}\n" );
						fwrite( $f, "# END {$marker}\n" );
						$state = true;
						$foundit = true;
					}
				}
			}
			if (!$foundit) {
				fwrite( $f, "\n# BEGIN {$marker}\n" );
				foreach ( $insertion as $insertline )
				fwrite( $f, "{$insertline}\n" );
				fwrite( $f, "# END {$marker}\n" );
			}
			fclose( $f );
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Updates the htaccess file with the current rules if it is writable.
	 *
	 * Always writes to the file if it exists and is writable to ensure that we blank out old rules.
	 */

	function save_mod_rewrite_rules() {
		global $wp_rewrite;

		$home_path = get_home_path();
		$htaccess_file = $home_path.'.htaccess';

		// If the file doesn't already exists check for write access to the directory and whether of not we have some rules.
		// else check for write access to the file.
		if ((!file_exists($htaccess_file) && is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks()) || is_writable($htaccess_file)) {
			if ( got_mod_rewrite() ) {
				$rules = explode( "\n", $wp_rewrite->mod_rewrite_rules() );
				return insert_with_markers( $htaccess_file, 'WordPress', $rules );
			}
		}

		return false;
	}

	function update_recently_edited( $file ) {
		$oldfiles = (array ) wpbasic::get_option( 'recently_edited' );
		if ( $oldfiles ) {
			$oldfiles = array_reverse( $oldfiles );
			$oldfiles[] = $file;
			$oldfiles = array_reverse( $oldfiles );
			$oldfiles = array_unique( $oldfiles );
			if ( 5 < count( $oldfiles ))
			array_pop( $oldfiles );
		} else {
			$oldfiles[] = $file;
		}
		update_option( 'recently_edited', $oldfiles );
	}

	// If siteurl or home changed, flush rewrite rules.
	function update_home_siteurl( $old_value, $value ) {
		global $wp_rewrite;

		if ( defined( "WP_INSTALLING" ) )
		return;

		// If home changed, write rewrite rules to new location.
		$wp_rewrite->flush_rules();
	}
	/* //TODO: what is this?
	 add_action( 'update_option_home', 'update_home_siteurl', 10, 2 );
	 add_action( 'update_option_siteurl', 'update_home_siteurl', 10, 2 );
	 //
	 function url_shorten( $url ) {
		$short_url = str_replace( 'http://', '', stripslashes( $url ));
		$short_url = str_replace( 'www.', '', $short_url );
		if ('/' == substr( $short_url, -1 ))
		$short_url = substr( $short_url, 0, -1 );
		if ( strlen( $short_url ) > 35 )
		$short_url = substr( $short_url, 0, 32 ).'...';
		return $short_url;
		}

		function wp_reset_vars( $vars ) {
		for ( $i=0; $i<count( $vars ); $i += 1 ) {
		$var = $vars[$i];
		global $$var;

		if (!isset( $$var ) ) {
		if ( empty( $_POST["$var"] ) ) {
		if ( empty( $_GET["$var"] ) )
		$$var = '';
		else
		$$var = $_GET["$var"];
		} else {
		$$var = $_POST["$var"];
		}
		}
		}
		}

		//////////  plugin.php  ///////////////


		function get_plugin_data( $plugin_file ) {
		$plugin_data = implode( '', file( $plugin_file ));
		preg_match( '|Plugin Name:(.*)$|mi', $plugin_data, $plugin_name );
		preg_match( '|Plugin URI:(.*)$|mi', $plugin_data, $plugin_uri );
		preg_match( '|Description:(.*)$|mi', $plugin_data, $description );
		preg_match( '|Author:(.*)$|mi', $plugin_data, $author_name );
		preg_match( '|Author URI:(.*)$|mi', $plugin_data, $author_uri );

		if ( preg_match( "|Version:(.*)|i", $plugin_data, $version ))
		$version = trim( $version[1] );
		else
		$version = '';

		$description = wptexturize( trim( $description[1] ));

		$name = $plugin_name[1];
		$name = trim( $name );
		$plugin = $name;
		if ('' != trim($plugin_uri[1]) && '' != $name ) {
		$plugin = '<a href="' . trim( $plugin_uri[1] ) . '" title="'.__( 'Visit plugin homepage' ).'">'.$plugin.'</a>';
		}

		if ('' == $author_uri[1] ) {
		$author = trim( $author_name[1] );
		} else {
		$author = '<a href="' . trim( $author_uri[1] ) . '" title="'.__( 'Visit author homepage' ).'">' . trim( $author_name[1] ) . '</a>';
		}

		return array('Name' => $name, 'Title' => $plugin, 'Description' => $description, 'Author' => $author, 'Version' => $version);
		}

		function get_plugins($plugin_folder = '') {

		if ( ! $cache_plugins = wp_cache_get('plugins', 'plugins') )
		$cache_plugins = array();

		if ( isset($cache_plugins[ $plugin_folder ]) )
		return $cache_plugins[ $plugin_folder ];

		$wp_plugins = array ();
		$plugin_root = WP_PLUGIN_DIR;
		if( !empty($plugin_folder) )
		$plugin_root .= $plugin_folder;

		// Files in wp-content/plugins directory
		$plugins_dir = @ opendir( $plugin_root);
		if ( $plugins_dir ) {
		while (($file = readdir( $plugins_dir ) ) !== false ) {
		if ( substr($file, 0, 1) == '.' )
		continue;
		if ( is_dir( $plugin_root.'/'.$file ) ) {
		$plugins_subdir = @ opendir( $plugin_root.'/'.$file );
		if ( $plugins_subdir ) {
		while (($subfile = readdir( $plugins_subdir ) ) !== false ) {
		if ( substr($subfile, 0, 1) == '.' )
		continue;
		if ( substr($subfile, -4) == '.php' )
		$plugin_files[] = "$file/$subfile";
		}
		}
		} else {
		if ( substr($file, -4) == '.php' )
		$plugin_files[] = $file;
		}
		}
		}
		@closedir( $plugins_dir );
		@closedir( $plugins_subdir );

		if ( !$plugins_dir || !$plugin_files )
		return $wp_plugins;

		foreach ( $plugin_files as $plugin_file ) {
		if ( !is_readable( "$plugin_root/$plugin_file" ) )
		continue;

		$plugin_data = get_plugin_data( "$plugin_root/$plugin_file" );

		if ( empty ( $plugin_data['Name'] ) )
		continue;

		$wp_plugins[plugin_basename( $plugin_file )] = $plugin_data;
		}

		uasort( $wp_plugins, create_function( '$a, $b', 'return strnatcasecmp( $a["Name"], $b["Name"] );' ));

		$cache_plugins[ $plugin_folder ] = $wp_plugins;
		wp_cache_set('plugins', $cache_plugins, 'plugins');

		return $wp_plugins;
		}

		function is_plugin_active($plugin){
		return in_array($plugin, wpbasic::get_option('active_plugins'));
		}

		function activate_plugin($plugin, $redirect = '') {
		$current = wpbasic::get_option('active_plugins');
		$plugin = trim($plugin);

		$valid = validate_plugin($plugin);
		if ( is_wp_error($valid) )
		return $valid;

		if ( !in_array($plugin, $current) ) {
		if ( !empty($redirect) )
		wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect)); // we'll override this later if the plugin can be included without fatal error
		ob_start();
		@include(WP_PLUGIN_DIR . '/' . $plugin);
		$current[] = $plugin;
		sort($current);
		update_option('active_plugins', $current);
		wpbasic::do_action('activate_' . $plugin);
		ob_end_clean();
		}

		return null;
		}

		function deactivate_plugins($plugins, $silent= false) {
		$current = wpbasic::get_option('active_plugins');

		if ( !is_array($plugins) )
		$plugins = array($plugins);

		foreach ( $plugins as $plugin ) {
		if( ! is_plugin_active($plugin) )
		continue;
		array_splice($current, array_search( $plugin, $current), 1 ); // Fixed Array-fu!
		if ( ! $silent ) //Used by Plugin updater to internally deactivate plugin, however, not to notify plugins of the fact to prevent plugin output.
		wpbasic::do_action('deactivate_' . trim( $plugin ));
		}

		update_option('active_plugins', $current);
		}

		function activate_plugins($plugins, $redirect = '') {
		if ( !is_array($plugins) )
		$plugins = array($plugins);

		$errors = array();
		foreach ( (array) $plugins as $plugin ) {
		if ( !empty($redirect) )
		$redirect = add_query_arg('plugin', $plugin, $redirect);
		$result = activate_plugin($plugin, $redirect);
		if ( is_wp_error($result) )
		$errors[$plugin] = $result;
		}

		if ( !empty($errors) )
		return new WP_Error('plugins_invalid', __('One of the plugins is invalid.'), $errors);

		return true;
		}

		function delete_plugins($plugins, $redirect = '' ) {
		global $wp_filesystem;

		if( empty($plugins) )
		return false;

		$checked = array();
		foreach( $plugins as $plugin )
		$checked[] = 'checked[]=' . $plugin;

		ob_start();
		$url = wp_nonce_url('plugins.php?action=delete-selected&verify-delete=1&' . implode('&', $checked), 'bulk-manage-plugins');
		if ( false === ($credentials = request_filesystem_credentials($url)) ) {
		$data = ob_get_contents();
		ob_end_clean();
		if( ! empty($data) ){
		include_once( ABSPATH . 'wp-admin/admin-header.php');
		echo $data;
		include( ABSPATH . 'wp-admin/admin-footer.php');
		exit;
		}
		return;
		}

		if ( ! WP_Filesystem($credentials) ) {
		request_filesystem_credentials($url, '', true); //Failed to connect, Error and request again
		$data = ob_get_contents();
		ob_end_clean();
		if( ! empty($data) ){
		include_once( ABSPATH . 'wp-admin/admin-header.php');
		echo $data;
		include( ABSPATH . 'wp-admin/admin-footer.php');
		exit;
		}
		return;
		}

		if ( $wp_filesystem->errors->get_error_code() ) {
		return $wp_filesystem->errors;
		}

		if ( ! is_object($wp_filesystem) )
		return new WP_Error('fs_unavailable', __('Could not access filesystem.'));

		if ( $wp_filesystem->errors->get_error_code() )
		return new WP_Error('fs_error', __('Filesystem error'), $wp_filesystem->errors);

		//Get the base plugin folder
		$plugins_dir = $wp_filesystem->wp_plugins_dir();
		if ( empty($plugins_dir) )
		return new WP_Error('fs_no_plugins_dir', __('Unable to locate WordPress Plugin directory.'));

		$plugins_dir = trailingslashit( $plugins_dir );

		$errors = array();

		foreach( $plugins as $plugin_file ) {
		$this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin_file) );
		// If plugin is in its own directory, recursively delete the directory.
		if ( strpos($plugin_file, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory seperator AND that its not the root plugin folder
		$deleted = $wp_filesystem->delete($this_plugin_dir, true);
		else
		$deleted = $wp_filesystem->delete($plugins_dir . $plugin_file);

		if ( ! $deleted )
		$errors[] = $plugin_file;
		}

		if( ! empty($errors) )
		return new WP_Error('could_not_remove_plugin', sprintf(__('Could not fully remove the plugin(s) %s'), implode(', ', $errors)) );

		return true;
		}

		function validate_active_plugins() {
		$check_plugins = wpbasic::get_option('active_plugins');

		// Sanity check.  If the active plugin list is not an array, make it an
		// empty array.
		if ( !is_array($check_plugins) ) {
		update_option('active_plugins', array());
		return;
		}

		//Invalid is any plugin that is deactivated due to error.
		$invalid = array();

		// If a plugin file does not exist, remove it from the list of active
		// plugins.
		foreach ( $check_plugins as $check_plugin ) {
		$result = validate_plugin($check_plugin);
		if ( is_wp_error( $result ) ) {
		$invalid[$check_plugin] = $result;
		deactivate_plugins( $check_plugin, true);
		}
		}
		return $invalid;
		}

		function validate_plugin($plugin) {
		if ( validate_file($plugin) )
		return new WP_Error('plugin_invalid', __('Invalid plugin.'));
		if ( ! file_exists(WP_PLUGIN_DIR . '/' . $plugin) )
		return new WP_Error('plugin_not_found', __('Plugin file does not exist.'));

		return 0;
		}

		//
		// Menu
		//

		function add_menu_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
		global $menu, $admin_page_hooks;

		$file = plugin_basename( $file );

		$menu[] = array ( $menu_title, $access_level, $file, $page_title );

		$admin_page_hooks[$file] = sanitize_title( $menu_title );

		$hookname = get_plugin_page_hookname( $file, '' );
		if (!empty ( $function ) && !empty ( $hookname ))
		add_action( $hookname, $function );

		return $hookname;
		}

		function add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function = '' ) {
		global $submenu;
		global $menu;
		global $_wp_real_parent_file;
		global $_wp_submenu_nopriv;

		$file = plugin_basename( $file );

		$parent = plugin_basename( $parent);
		if ( isset( $_wp_real_parent_file[$parent] ) )
		$parent = $_wp_real_parent_file[$parent];

		if ( !current_user_can( $access_level ) ) {
		$_wp_submenu_nopriv[$parent][$file] = true;
		return false;
		}

		// If the parent doesn't already have a submenu, add a link to the parent
		// as the first item in the submenu.  If the submenu file is the same as the
		// parent file someone is trying to link back to the parent manually.  In
		// this case, don't automatically add a link back to avoid duplication.
		if (!isset( $submenu[$parent] ) && $file != $parent  ) {
		foreach ( $menu as $parent_menu ) {
		if ( $parent_menu[2] == $parent && current_user_can( $parent_menu[1] ) )
		$submenu[$parent][] = $parent_menu;
		}
		}

		$submenu[$parent][] = array ( $menu_title, $access_level, $file, $page_title );

		$hookname = get_plugin_page_hookname( $file, $parent);
		if (!empty ( $function ) && !empty ( $hookname ))
		add_action( $hookname, $function );

		return $hookname;
		}

		function add_management_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
		return add_submenu_page( 'edit.php', $page_title, $menu_title, $access_level, $file, $function );
		}

		function add_options_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
		return add_submenu_page( 'options-general.php', $page_title, $menu_title, $access_level, $file, $function );
		}

		function add_theme_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
		return add_submenu_page( 'themes.php', $page_title, $menu_title, $access_level, $file, $function );
		}

		function add_users_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
		if ( current_user_can('edit_users') )
		$parent = 'users.php';
		else
		$parent = 'profile.php';
		return add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function );
		}

		//
		// Pluggable Menu Support -- Private
		//

		function get_admin_page_parent() {
		global $parent_file;
		global $menu;
		global $submenu;
		global $pagenow;
		global $plugin_page;
		global $_wp_real_parent_file;
		global $_wp_menu_nopriv;
		global $_wp_submenu_nopriv;

		if ( !empty ( $parent_file ) ) {
		if ( isset( $_wp_real_parent_file[$parent_file] ) )
		$parent_file = $_wp_real_parent_file[$parent_file];

		return $parent_file;
		}

		if ( $pagenow == 'admin.php' && isset( $plugin_page ) ) {
		foreach ( $menu as $parent_menu ) {
		if ( $parent_menu[2] == $plugin_page ) {
		$parent_file = $plugin_page;
		if ( isset( $_wp_real_parent_file[$parent_file] ) )
		$parent_file = $_wp_real_parent_file[$parent_file];
		return $parent_file;
		}
		}
		if ( isset( $_wp_menu_nopriv[$plugin_page] ) ) {
		$parent_file = $plugin_page;
		if ( isset( $_wp_real_parent_file[$parent_file] ) )
		$parent_file = $_wp_real_parent_file[$parent_file];
		return $parent_file;
		}
		}

		if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) ) {
		$parent_file = $pagenow;
		if ( isset( $_wp_real_parent_file[$parent_file] ) )
		$parent_file = $_wp_real_parent_file[$parent_file];
		return $parent_file;
		}

		foreach (array_keys( $submenu ) as $parent) {
		foreach ( $submenu[$parent] as $submenu_array ) {
		if ( isset( $_wp_real_parent_file[$parent] ) )
		$parent = $_wp_real_parent_file[$parent];
		if ( $submenu_array[2] == $pagenow ) {
		$parent_file = $parent;
		return $parent;
		} else
		if ( isset( $plugin_page ) && ($plugin_page == $submenu_array[2] ) ) {
		$parent_file = $parent;
		return $parent;
		}
		}
		}

		$parent_file = '';
		return '';
		}

		function get_admin_page_title() {
		global $title;
		global $menu;
		global $submenu;
		global $pagenow;
		global $plugin_page;

		if ( isset( $title ) && !empty ( $title ) ) {
		return $title;
		}

		$hook = get_plugin_page_hook( $plugin_page, $pagenow );

		$parent = $parent1 = get_admin_page_parent();
		if ( empty ( $parent) ) {
		foreach ( $menu as $menu_array ) {
		if ( isset( $menu_array[3] ) ) {
		if ( $menu_array[2] == $pagenow ) {
		$title = $menu_array[3];
		return $menu_array[3];
		} else
		if ( isset( $plugin_page ) && ($plugin_page == $menu_array[2] ) && ($hook == $menu_array[3] ) ) {
		$title = $menu_array[3];
		return $menu_array[3];
		}
		} else {
		$title = $menu_array[0];
		return $title;
		}
		}
		} else {
		foreach (array_keys( $submenu ) as $parent) {
		foreach ( $submenu[$parent] as $submenu_array ) {
		if ( isset( $plugin_page ) &&
		($plugin_page == $submenu_array[2] ) &&
		(($parent == $pagenow ) || ($parent == $plugin_page ) || ($plugin_page == $hook ) || (($pagenow == 'admin.php' ) && ($parent1 != $submenu_array[2] ) ) )
		) {
		$title = $submenu_array[3];
		return $submenu_array[3];
		}

		if ( $submenu_array[2] != $pagenow || isset( $_GET['page'] ) ) // not the current page
		continue;

		if ( isset( $submenu_array[3] ) ) {
		$title = $submenu_array[3];
		return $submenu_array[3];
		} else {
		$title = $submenu_array[0];
		return $title;
		}
		}
		}
		}

		return $title;
		}

		function get_plugin_page_hook( $plugin_page, $parent_page ) {
		$hook = get_plugin_page_hookname( $plugin_page, $parent_page );
		if ( has_action($hook) )
		return $hook;
		else
		return null;
		}

		function get_plugin_page_hookname( $plugin_page, $parent_page ) {
		global $admin_page_hooks;

		$parent = get_admin_page_parent();

		$page_type = 'admin';
		if ( empty ( $parent_page ) || 'admin.php' == $parent_page ) {
		if ( isset( $admin_page_hooks[$plugin_page] ))
		$page_type = 'toplevel';
		else
		if ( isset( $admin_page_hooks[$parent] ))
		$page_type = $admin_page_hooks[$parent];
		} else if ( isset( $admin_page_hooks[$parent_page] ) ) {
		$page_type = $admin_page_hooks[$parent_page];
		}

		$plugin_name = preg_replace( '!\.php!', '', $plugin_page );

		return $page_type.'_page_'.$plugin_name;
		}

		function user_can_access_admin_page() {
		global $pagenow;
		global $menu;
		global $submenu;
		global $_wp_menu_nopriv;
		global $_wp_submenu_nopriv;
		global $plugin_page;

		$parent = get_admin_page_parent();

		if ( isset( $_wp_submenu_nopriv[$parent][$pagenow] ) )
		return false;

		if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$parent][$plugin_page] ) )
		return false;

		if ( empty( $parent) ) {
		if ( isset( $_wp_menu_nopriv[$pagenow] ) )
		return false;
		if ( isset( $_wp_submenu_nopriv[$pagenow][$pagenow] ) )
		return false;
		if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) )
		return false;
		foreach (array_keys( $_wp_submenu_nopriv ) as $key ) {
		if ( isset( $_wp_submenu_nopriv[$key][$pagenow] ) )
		return false;
		if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$key][$plugin_page] ) )
		return false;
		}
		return true;
		}

		if ( isset( $submenu[$parent] ) ) {
		foreach ( $submenu[$parent] as $submenu_array ) {
		if ( isset( $plugin_page ) && ( $submenu_array[2] == $plugin_page ) ) {
		if ( current_user_can( $submenu_array[1] ))
		return true;
		else
		return false;
		} else if ( $submenu_array[2] == $pagenow ) {
		if ( current_user_can( $submenu_array[1] ))
		return true;
		else
		return false;
		}
		}
		}

		foreach ( $menu as $menu_array ) {
		if ( $menu_array[2] == $parent) {
		if ( current_user_can( $menu_array[1] ))
		return true;
		else
		return false;
		}
		}

		return true;
		}

		//////////////  post.php ////////////////////////////


		/**
	 * _wp_translate_postdata() - Rename $_POST data from form names to DB post columns.
	 *
	 * Manipulates $_POST directly.
	 *
	 * @package WordPress
	 * @since 2.6
	 *
	 * @param bool $update Are we updating a pre-existing post?
	 * @return object|bool WP_Error on failure, true on success.
	 */
	function _wp_translate_postdata( $update = false ) {
		if ( $update )
		$_POST['ID'] = (int) $_POST['post_ID'];
		$_POST['post_content'] = $_POST['content'];
		$_POST['post_excerpt'] = $_POST['excerpt'];
		$_POST['post_parent'] = isset($_POST['parent_id'])? $_POST['parent_id'] : '';
		$_POST['to_ping'] = $_POST['trackback_url'];

		if (!empty ( $_POST['post_author_override'] ) ) {
			$_POST['post_author'] = (int) $_POST['post_author_override'];
		} else {
			if (!empty ( $_POST['post_author'] ) ) {
				$_POST['post_author'] = (int) $_POST['post_author'];
			} else {
				$_POST['post_author'] = (int) $_POST['user_ID'];
			}
		}

		if ( $_POST['post_author'] != $_POST['user_ID'] ) {
			if ( 'page' == $_POST['post_type'] ) {
				if ( !current_user_can( 'edit_others_pages' ) ) {
					return new WP_Error( 'edit_others_pages', $update ?
					__( 'You are not allowed to edit pages as this user.' ) :
					__( 'You are not allowed to create pages as this user.' )
					);
				}
			} else {
				if ( !current_user_can( 'edit_others_posts' ) ) {
					return new WP_Error( 'edit_others_posts', $update ?
					__( 'You are not allowed to edit posts as this user.' ) :
					__( 'You are not allowed to post as this user.' )
					);
				}
			}
		}

		// What to do based on which button they pressed
		if ( isset($_POST['saveasdraft']) && '' != $_POST['saveasdraft'] )
		$_POST['post_status'] = 'draft';
		if ( isset($_POST['saveasprivate']) && '' != $_POST['saveasprivate'] )
		$_POST['post_status'] = 'private';
		if ( isset($_POST['publish']) && ( '' != $_POST['publish'] ) && ( $_POST['post_status'] != 'private' ) )
		$_POST['post_status'] = 'publish';
		if ( isset($_POST['advanced']) && '' != $_POST['advanced'] )
		$_POST['post_status'] = 'draft';

		$previous_status = get_post_field('post_status',  $_POST['ID']);

		// Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
		// Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
		if ( 'page' == $_POST['post_type'] ) {
			if ( 'publish' == $_POST['post_status'] && !current_user_can( 'publish_pages' ) )
			if ( $previous_status != 'publish' OR !current_user_can( 'edit_published_pages') )
			$_POST['post_status'] = 'pending';
		} else {
			if ( 'publish' == $_POST['post_status'] && !current_user_can( 'publish_posts' ) ) :
			// Stop attempts to publish new posts, but allow already published posts to be saved if appropriate.
			if ( $previous_status != 'publish' OR !current_user_can( 'edit_published_posts') )
			$_POST['post_status'] = 'pending';
			endif;
		}

		if (!isset( $_POST['comment_status'] ))
		$_POST['comment_status'] = 'closed';

		if (!isset( $_POST['ping_status'] ))
		$_POST['ping_status'] = 'closed';

		foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
			if ( !empty( $_POST['hidden_' . $timeunit] ) && $_POST['hidden_' . $timeunit] != $_POST[$timeunit] ) {
				$_POST['edit_date'] = '1';
				break;
			}
		}

		if ( !empty( $_POST['edit_date'] ) ) {
			$aa = $_POST['aa'];
			$mm = $_POST['mm'];
			$jj = $_POST['jj'];
			$hh = $_POST['hh'];
			$mn = $_POST['mn'];
			$ss = $_POST['ss'];
			$aa = ($aa <= 0 ) ? date('Y') : $aa;
			$mm = ($mm <= 0 ) ? date('n') : $mm;
			$jj = ($jj > 31 ) ? 31 : $jj;
			$jj = ($jj <= 0 ) ? date('j') : $jj;
			$hh = ($hh > 23 ) ? $hh -24 : $hh;
			$mn = ($mn > 59 ) ? $mn -60 : $mn;
			$ss = ($ss > 59 ) ? $ss -60 : $ss;
			$_POST['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss );
			$_POST['post_date_gmt'] = get_gmt_from_date( $_POST['post_date'] );
		}

		return true;
	}


	// Update an existing post with values provided in $_POST.
	function edit_post() {

		$post_ID = (int) $_POST['post_ID'];

		if ( 'page' == $_POST['post_type'] ) {
			if ( !current_user_can( 'edit_page', $post_ID ) )
			wp_die( __('You are not allowed to edit this page.' ));
		} else {
			if ( !current_user_can( 'edit_post', $post_ID ) )
			wp_die( __('You are not allowed to edit this post.' ));
		}

		// Autosave shouldn't save too soon after a real save
		if ( 'autosave' == $_POST['action'] ) {
			$post =& get_post( $post_ID );
			$now = time();
			$then = strtotime($post->post_date_gmt . ' +0000');
			$delta = AUTOSAVE_INTERVAL / 2;
			if ( ($now - $then) < $delta )
			return $post_ID;
		}

		$translated = _wp_translate_postdata( true );
		if ( is_wp_error($translated) )
		wp_die( $translated->get_error_message() );

		// Meta Stuff
		if ( isset($_POST['meta']) && $_POST['meta'] ) {
			foreach ( $_POST['meta'] as $key => $value )
			update_meta( $key, $value['key'], $value['value'] );
		}

		if ( isset($_POST['deletemeta']) && $_POST['deletemeta'] ) {
			foreach ( $_POST['deletemeta'] as $key => $value )
			delete_meta( $key );
		}

		add_meta( $post_ID );

		wp_update_post( $_POST );

		// Reunite any orphaned attachments with their parent
		if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) )
		$draft_ids = array();
		if ( $draft_temp_id = (int) array_search( $post_ID, $draft_ids ) )
		_relocate_children( $draft_temp_id, $post_ID );

		// Now that we have an ID we can fix any attachment anchor hrefs
		_fix_attachment_links( $post_ID );

		wp_set_post_lock( $post_ID, $GLOBALS['current_user']->ID );

		return $post_ID;
	}

	// Default post information to use when populating the "Write Post" form.
	function get_default_post_to_edit() {
		if ( !empty( $_REQUEST['post_title'] ) )
		$post_title = wp_specialchars( stripslashes( $_REQUEST['post_title'] ));
		else if ( !empty( $_REQUEST['popuptitle'] ) ) {
			$post_title = wp_specialchars( stripslashes( $_REQUEST['popuptitle'] ));
			$post_title = funky_javascript_fix( $post_title );
		} else {
			$post_title = '';
		}

		$post_content = '';
		if ( !empty( $_REQUEST['content'] ) )
		$post_content = wp_specialchars( stripslashes( $_REQUEST['content'] ));
		else if ( !empty( $post_title ) ) {
			$text       = wp_specialchars( stripslashes( urldecode( $_REQUEST['text'] ) ) );
			$text       = funky_javascript_fix( $text);
			$popupurl   = clean_url($_REQUEST['popupurl']);
			$post_content = '<a href="'.$popupurl.'">'.$post_title.'</a>'."\n$text";
		}

		if ( !empty( $_REQUEST['excerpt'] ) )
		$post_excerpt = wp_specialchars( stripslashes( $_REQUEST['excerpt'] ));
		else
		$post_excerpt = '';

		$post->ID = 0;
		$post->post_name = '';
		$post->post_author = '';
		$post->post_date = '';
		$post->post_status = 'draft';
		$post->post_type = 'post';
		$post->to_ping = '';
		$post->pinged = '';
		$post->comment_status = wpbasic::get_option( 'default_comment_status' );
		$post->ping_status = wpbasic::get_option( 'default_ping_status' );
		$post->post_pingback = wpbasic::get_option( 'default_pingback_flag' );
		$post->post_category = wpbasic::get_option( 'default_category' );
		$post->post_content = wpbasic::apply_filters( 'default_content', $post_content);
		$post->post_title = wpbasic::apply_filters( 'default_title', $post_title );
		$post->post_excerpt = wpbasic::apply_filters( 'default_excerpt', $post_excerpt);
		$post->page_template = 'default';
		$post->post_parent = 0;
		$post->menu_order = 0;

		return $post;
	}

	function get_default_page_to_edit() {
		$page = get_default_post_to_edit();
		$page->post_type = 'page';
		return $page;
	}

	// Get an existing post and format it for editing.
	function get_post_to_edit( $id ) {

		$post = get_post( $id, OBJECT, 'edit' );

		if ( $post->post_type == 'page' )
		$post->page_template = get_post_meta( $id, '_wp_page_template', true );

		return $post;
	}

	function post_exists($title, $content = '', $post_date = '') {
		$wpdb = JWPBlog::getWpdb();

		if (!empty ($post_date))
		$post_date = $wpdb->prepare("AND post_date = %s", $post_date);

		if (!empty ($title))
		return $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title = %s $post_date", $title) );
		else
		if (!empty ($content))
		return $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_content = %s $post_date", $content) );

		return 0;
	}

	// Creates a new post from the "Write Post" form using $_POST information.
	function wp_write_post() {
		global $user_ID;

		if ( 'page' == $_POST['post_type'] ) {
			if ( !current_user_can( 'edit_pages' ) )
			return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this blog.' ) );
		} else {
			if ( !current_user_can( 'edit_posts' ) )
			return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this blog.' ) );
		}


		// Check for autosave collisions
		$temp_id = false;
		if ( isset($_POST['temp_ID']) ) {
			$temp_id = (int) $_POST['temp_ID'];
			if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) )
			$draft_ids = array();
			foreach ( $draft_ids as $temp => $real )
			if ( time() + $temp > 86400 ) // 1 day: $temp is equal to -1 * time( then )
			unset($draft_ids[$temp]);

			if ( isset($draft_ids[$temp_id]) ) { // Edit, don't write
				$_POST['post_ID'] = $draft_ids[$temp_id];
				unset($_POST['temp_ID']);
				update_user_option( $user_ID, 'autosave_draft_ids', $draft_ids );
				return edit_post();
			}
		}

		$translated = _wp_translate_postdata( false );
		if ( is_wp_error($translated) )
		return $translated;

		// Create the post.
		$post_ID = wp_insert_post( $_POST );
		if ( is_wp_error( $post_ID ) )
		return $post_ID;

		if ( empty($post_ID) )
		return 0;

		add_meta( $post_ID );

		// Reunite any orphaned attachments with their parent
		if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) )
		$draft_ids = array();
		if ( $draft_temp_id = (int) array_search( $post_ID, $draft_ids ) )
		_relocate_children( $draft_temp_id, $post_ID );
		if ( $temp_id && $temp_id != $draft_temp_id )
		_relocate_children( $temp_id, $post_ID );

		// Update autosave collision detection
		if ( $temp_id ) {
			$draft_ids[$temp_id] = $post_ID;
			update_user_option( $user_ID, 'autosave_draft_ids', $draft_ids );
		}

		// Now that we have an ID we can fix any attachment anchor hrefs
		_fix_attachment_links( $post_ID );

		wp_set_post_lock( $post_ID, $GLOBALS['current_user']->ID );

		return $post_ID;
	}

	function write_post() {
		$result = wp_write_post();
		if( is_wp_error( $result ) )
		wp_die( $result->get_error_message() );
		else
		return $result;
	}

	//
	// Post Meta
	//

	function add_meta( $post_ID ) {
		$wpdb = JWPBlog::getWpdb();
		$post_ID = (int) $post_ID;

		$protected = array( '_wp_attached_file', '_wp_attachment_metadata', '_wp_old_slug', '_wp_page_template' );

		$metakeyselect = $wpdb->escape( stripslashes( trim( $_POST['metakeyselect'] ) ) );
		$metakeyinput = $wpdb->escape( stripslashes( trim( $_POST['metakeyinput'] ) ) );
		$metavalue = maybe_serialize( stripslashes( (trim( $_POST['metavalue'] ) ) ));
		$metavalue = $wpdb->escape( $metavalue );

		if ( ('0' === $metavalue || !empty ( $metavalue ) ) && ((('#NONE#' != $metakeyselect) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput) ) ) {
			// We have a key/value pair. If both the select and the
			// input for the key have data, the input takes precedence:

			if ('#NONE#' != $metakeyselect)
			$metakey = $metakeyselect;

			if ( $metakeyinput)
			$metakey = $metakeyinput; // default

			if ( in_array($metakey, $protected) )
			return false;

			wp_cache_delete($post_ID, 'post_meta');

			$wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->postmeta
			(post_id,meta_key,meta_value ) VALUES (%s, %s, %s)",
			$post_ID, $metakey, $metavalue) );
			return $wpdb->insert_id;
		}
		return false;
	} // add_meta

	function delete_meta( $mid ) {
		$wpdb = JWPBlog::getWpdb();
		$mid = (int) $mid;

		$post_id = $wpdb->get_var( $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_id = %d", $mid) );
		wp_cache_delete($post_id, 'post_meta');

		return $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id = %d", $mid) );
	}

	// Get a list of previously defined keys
	function get_meta_keys() {
		$wpdb = JWPBlog::getWpdb();

		$keys = $wpdb->get_col( "
		SELECT meta_key
		FROM $wpdb->postmeta
		GROUP BY meta_key
		ORDER BY meta_key" );

		return $keys;
	}

	function get_post_meta_by_id( $mid ) {
		$wpdb = JWPBlog::getWpdb();
		$mid = (int) $mid;

		$meta = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_id = %d", $mid) );
		if ( is_serialized_string( $meta->meta_value ) )
		$meta->meta_value = maybe_unserialize( $meta->meta_value );
		return $meta;
	}

	// Some postmeta stuff
	function has_meta( $postid ) {
		$wpdb = JWPBlog::getWpdb();

		return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
		FROM $wpdb->postmeta WHERE post_id = %d
		ORDER BY meta_key,meta_id", $postid), ARRAY_A );

	}

	function update_meta( $meta_id, $meta_key, $meta_value ) {
		$wpdb = JWPBlog::getWpdb();

		$protected = array( '_wp_attached_file', '_wp_attachment_metadata', '_wp_old_slug', '_wp_page_template' );

		if ( in_array($meta_key, $protected) )
		return false;

		$post_id = $wpdb->get_var( $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_id = %d", $meta_id) );
		wp_cache_delete($post_id, 'post_meta');

		$meta_value = maybe_serialize( stripslashes( $meta_value ));
		$meta_id = (int) $meta_id;

		$data  = compact( 'meta_key', 'meta_value' );
		$where = compact( 'meta_id' );

		return $wpdb->update( $wpdb->postmeta, $data, $where );
	}

	//
	// Private
	//

	// Replace hrefs of attachment anchors with up-to-date permalinks.
	function _fix_attachment_links( $post_ID ) {

		$post = & get_post( $post_ID, ARRAY_A );

		$search = "#<a[^>]+rel=('|\")[^'\"]*attachment[^>]*>#ie";

		// See if we have any rel="attachment" links
		if ( 0 == preg_match_all( $search, $post['post_content'], $anchor_matches, PREG_PATTERN_ORDER ) )
		return;

		$i = 0;
		$search = "#[\s]+rel=(\"|')(.*?)wp-att-(\d+)\\1#i";
		foreach ( $anchor_matches[0] as $anchor ) {
			if ( 0 == preg_match( $search, $anchor, $id_matches ) )
			continue;

			$id = (int) $id_matches[3];

			// While we have the attachment ID, let's adopt any orphans.
			$attachment = & get_post( $id, ARRAY_A );
			if ( ! empty( $attachment) && ! is_object( get_post( $attachment['post_parent'] ) ) ) {
				$attachment['post_parent'] = $post_ID;
				// Escape data pulled from DB.
				$attachment = add_magic_quotes( $attachment);
				wp_update_post( $attachment);
			}

			$post_search[$i] = $anchor;
			$post_replace[$i] = preg_replace( "#href=(\"|')[^'\"]*\\1#e", "stripslashes( 'href=\\1' ).get_attachment_link( $id ).stripslashes( '\\1' )", $anchor );
			++$i;
		}

		$post['post_content'] = str_replace( $post_search, $post_replace, $post['post_content'] );

		// Escape data pulled from DB.
		$post = add_magic_quotes( $post);

		return wp_update_post( $post);
	}

	// Move child posts to a new parent
	function _relocate_children( $old_ID, $new_ID ) {
		$wpdb = JWPBlog::getWpdb();
		$old_ID = (int) $old_ID;
		$new_ID = (int) $new_ID;
		return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_parent = %d WHERE post_parent = %d", $new_ID, $old_ID) );
	}

	function get_available_post_statuses($type = 'post') {
		$stati = wp_count_posts($type);

		return array_keys(get_object_vars($stati));
	}

	function wp_edit_posts_query( $q = false ) {
		$wpdb = JWPBlog::getWpdb();
		if ( false === $q )
		$q = $_GET;
		$q['m']   = (int) $q['m'];
		$q['cat'] = (int) $q['cat'];
		$post_stati  = array(	//	array( adj, noun )
				'publish' => array(__('Published'), __('Published posts'), __ngettext_noop('Published (%s)', 'Published (%s)')),
				'future' => array(__('Scheduled'), __('Scheduled posts'), __ngettext_noop('Scheduled (%s)', 'Scheduled (%s)')),
				'pending' => array(__('Pending Review'), __('Pending posts'), __ngettext_noop('Pending Review (%s)', 'Pending Review (%s)')),
				'draft' => array(__('Draft'), _c('Drafts|manage posts header'), __ngettext_noop('Draft (%s)', 'Drafts (%s)')),
				'private' => array(__('Private'), __('Private posts'), __ngettext_noop('Private (%s)', 'Private (%s)')),
		);

		$post_stati = wpbasic::apply_filters('post_stati', $post_stati);

		$avail_post_stati = get_available_post_statuses('post');

		$post_status_q = '';
		if ( isset($q['post_status']) && in_array( $q['post_status'], array_keys($post_stati) ) ) {
			$post_status_q = '&post_status=' . $q['post_status'];
			$post_status_q .= '&perm=readable';
		}

		if ( 'pending' === $q['post_status'] ) {
			$order = 'ASC';
			$orderby = 'modified';
		} elseif ( 'draft' === $q['post_status'] ) {
			$order = 'DESC';
			$orderby = 'modified';
		} else {
			$order = 'DESC';
			$orderby = 'date';
		}

		wp("post_type=post&what_to_show=posts$post_status_q&posts_per_page=15&order=$order&orderby=$orderby");

		return array($post_stati, $avail_post_stati);
	}

	function get_available_post_mime_types($type = 'attachment') {
		$wpdb = JWPBlog::getWpdb();

		$types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
		return $types;
	}

	function wp_edit_attachments_query( $q = false ) {
		$wpdb = JWPBlog::getWpdb();
		if ( false === $q )
		$q = $_GET;
		$q['m']   = (int) $q['m'];
		$q['cat'] = (int) $q['cat'];
		$q['post_type'] = 'attachment';
		$q['post_status'] = 'any';
		$q['posts_per_page'] = 15;
		$post_mime_types = array(	//	array( adj, noun )
				'image' => array(__('Images'), __('Manage Images'), __ngettext_noop('Image (%s)', 'Images (%s)')),
				'audio' => array(__('Audio'), __('Manage Audio'), __ngettext_noop('Audio (%s)', 'Audio (%s)')),
				'video' => array(__('Video'), __('Manage Video'), __ngettext_noop('Video (%s)', 'Video (%s)')),
		);
		$post_mime_types = wpbasic::apply_filters('post_mime_types', $post_mime_types);

		$avail_post_mime_types = get_available_post_mime_types('attachment');

		if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) )
		unset($q['post_mime_type']);

		wp($q);

		return array($post_mime_types, $avail_post_mime_types);
	}

	function postbox_classes( $id, $page ) {
		$current_user = wp_get_current_user();
		if ( $closed = get_usermeta( $current_user->ID, 'closedpostboxes_'.$page ) ) {
			if ( !is_array( $closed ) ) return '';
			return in_array( $id, $closed )? 'if-js-closed' : '';
		} else {
			if ( 'tagsdiv' == $id || 'categorydiv' == $id ) return '';
			else return 'if-js-closed';
		}
	}

	function get_sample_permalink($id, $title=null, $name = null) {
		$post = &get_post($id);
		if (!$post->ID) {
			return array('', '');
		}
		$original_status = $post->post_status;
		$original_date = $post->post_date;
		$original_name = $post->post_name;

		// Hack: get_permalink would return ugly permalink for
		// drafts, so we will fake, that our post is published
		if (in_array($post->post_status, array('draft', 'pending'))) {
			$post->post_status = 'publish';
			$post->post_date = date('Y-m-d H:i:s');
			$post->post_name = sanitize_title($post->post_name? $post->post_name : $post->post_title, $post->ID);
		}

		// If the user wants to set a new name -- override the current one
		// Note: if empty name is supplied -- use the title instead, see #6072
		if (!is_null($name)) {
			$post->post_name = sanitize_title($name? $name : $title, $post->ID);
		}

		$permalink = get_permalink($post, true);

		// Handle page hierarchy
		if ( 'page' == $post->post_type ) {
			$uri = get_page_uri($post->ID);
			$uri = untrailingslashit($uri);
			$uri = strrev( stristr( strrev( $uri ), '/' ) );
			$uri = untrailingslashit($uri);
			$uri = ( !empty($uri) )? $uri .='/': $uri;
			$permalink = str_replace('%pagename%', "${uri}%pagename%", $permalink);
	}
	$permalink = array($permalink, wpbasic::apply_filters('editable_slug', $post->post_name));
	$post->post_status = $original_status;
	$post->post_date = $original_date;
	$post->post_name = $original_name;
	return $permalink;
}

function get_sample_permalink_html($id, $new_title=null, $new_slug=null) {
	$post = &get_post($id);
	list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
	if (false === strpos($permalink, '%postname%') && false === strpos($permalink, '%pagename%')) {
		return '';
	}
	$title = __('Click to edit this part of the permalink');
	if (strlen($post_name) > 30) {
		$post_name_abridged = substr($post_name, 0, 14). '&hellip;' . substr($post_name, -14);
	} else {
		$post_name_abridged = $post_name;
	}
	$post_name_html = '<span id="editable-post-name" title="'.$title.'">'.$post_name_abridged.'</span><span id="editable-post-name-full">'.$post_name.'</span>';
	$display_link = str_replace(array('%pagename%','%postname%'), $post_name_html, $permalink);
	$return = '<strong>' . __('Permalink:') . "</strong>\n" . '<span id="sample-permalink">' . $display_link . "</span>\n";
	$return .= '<span id="edit-slug-buttons"><a href="#post_name" class="edit-slug" onclick="edit_permalink(' . $id . '); return false;">' . __('Edit') . "</a></span>\n";
	return $return;
}

// false: not locked or locked by current user
// int: user ID of user with lock
function wp_check_post_lock( $post_id ) {
	global $current_user;

	if ( !$post = get_post( $post_id ) )
	return false;

	$lock = get_post_meta( $post->ID, '_edit_lock', true );
	$last = get_post_meta( $post->ID, '_edit_last', true );

	$time_window = wpbasic::apply_filters( 'wp_check_post_lock_window', AUTOSAVE_INTERVAL * 2 );

	if ( $lock && $lock > time() - $time_window && $last != $current_user->ID )
	return $last;
	return false;
}

function wp_set_post_lock( $post_id ) {
	global $current_user;
	if ( !$post = get_post( $post_id ) )
	return false;
	if ( !$current_user || !$current_user->ID )
	return false;

	$now = time();

	if ( !add_post_meta( $post->ID, '_edit_lock', $now, true ) )
	update_post_meta( $post->ID, '_edit_lock', $now );
	if ( !add_post_meta( $post->ID, '_edit_last', $current_user->ID, true ) )
	update_post_meta( $post->ID, '_edit_last', $current_user->ID );
}

/**
 * wp_create_post_autosave() - creates autosave data for the specified post from $_POST data
 *
 * @package WordPress
 * @subpackage Post Revisions
 * @since 2.6
 *
 * @uses _wp_translate_postdata()
 * @uses _wp_post_revision_fields()
 */
function wp_create_post_autosave( $post_id ) {
	$translated = _wp_translate_postdata( true );
	if ( is_wp_error( $translated ) )
	return $translated;

	// Only store one autosave.  If there is already an autosave, overwrite it.
	if ( $old_autosave = wp_get_post_autosave( $post_id ) ) {
		$new_autosave = _wp_post_revision_fields( $_POST, true );
		$new_autosave['ID'] = $old_autosave->ID;
		return wp_update_post( $new_autosave );
	}

	// Otherwise create the new autosave as a special post revision
	return _wp_put_post_revision( $_POST, true );
}
//////////////////////// taxonomy.php  /////////////////////


//
// Category
//

function category_exists($cat_name) {
	$id = is_term($cat_name, 'category');
	if ( is_array($id) )
	$id = $id['term_id'];
	return $id;
}

function get_category_to_edit( $id ) {
	$category = get_category( $id, OBJECT, 'edit' );
	return $category;
}

function wp_create_category( $cat_name, $parent = 0 ) {
	if ( $id = category_exists($cat_name) )
	return $id;

	return wp_insert_category( array('cat_name' => $cat_name, 'category_parent' => $parent) );
}

function wp_create_categories($categories, $post_id = '') {
	$cat_ids = array ();
	foreach ($categories as $category) {
		if ($id = category_exists($category))
		$cat_ids[] = $id;
		else
		if ($id = wp_create_category($category))
		$cat_ids[] = $id;
	}

	if ($post_id)
	wp_set_post_categories($post_id, $cat_ids);

	return $cat_ids;
}

function wp_delete_category($cat_ID) {
	$cat_ID = (int) $cat_ID;
	$default = wpbasic::get_option('default_category');

	// Don't delete the default cat
	if ( $cat_ID == $default )
	return 0;

	return wp_delete_term($cat_ID, 'category', array('default' => $default));
}

function wp_insert_category($catarr, $wp_error = false) {
	$cat_defaults = array('cat_ID' => 0, 'cat_name' => '', 'category_description' => '', 'category_nicename' => '', 'category_parent' => '');
	$cat_arr = wp_parse_args($cat_arr, $cat_defaults);
	extract($catarr, EXTR_SKIP);

	if ( trim( $cat_name ) == '' ) {
		if ( ! $wp_error )
		return 0;
		else
		return new WP_Error( 'cat_name', __('You did not enter a category name.') );
	}

	$cat_ID = (int) $cat_ID;

	// Are we updating or creating?
	if ( !empty ($cat_ID) )
	$update = true;
	else
	$update = false;

	$name = $cat_name;
	$description = $category_description;
	$slug = $category_nicename;
	$parent = $category_parent;

	$parent = (int) $parent;
	if ( $parent < 0 )
	$parent = 0;

	if ( empty($parent) || !category_exists( $parent ) || ($cat_ID && cat_is_ancestor_of($cat_ID, $parent) ) )
	$parent = 0;

	$args = compact('name', 'slug', 'parent', 'description');

	if ( $update )
	$cat_ID = wp_update_term($cat_ID, 'category', $args);
	else
	$cat_ID = wp_insert_term($cat_name, 'category', $args);

	if ( is_wp_error($cat_ID) ) {
		if ( $wp_error )
		return $cat_ID;
		else
		return 0;
	}

	return $cat_ID['term_id'];
}

function wp_update_category($catarr) {
	$cat_ID = (int) $catarr['cat_ID'];

	if ( $cat_ID == $catarr['category_parent'] )
	return false;

	// First, get all of the original fields
	$category = get_category($cat_ID, ARRAY_A);

	// Escape data pulled from DB.
	$category = add_magic_quotes($category);

	// Merge old and new fields with new fields overwriting old ones.
	$catarr = array_merge($category, $catarr);

	return wp_insert_category($catarr);
}

//
// Tags
//

function get_tags_to_edit( $post_id ) {
	$post_id = (int) $post_id;
	if ( !$post_id )
	return false;

	$tags = wp_get_post_tags($post_id);

	if ( !$tags )
	return false;

	foreach ( $tags as $tag )
	$tag_names[] = $tag->name;
	$tags_to_edit = join( ',', $tag_names );
	$tags_to_edit = attribute_escape( $tags_to_edit );
	$tags_to_edit = wpbasic::apply_filters( 'tags_to_edit', $tags_to_edit );
	return $tags_to_edit;
}

function tag_exists($tag_name) {
	return is_term($tag_name, 'post_tag');
}

function wp_create_tag($tag_name) {
	if ( $id = tag_exists($tag_name) )
	return $id;

	return wp_insert_term($tag_name, 'post_tag');
}

///////////// template.php ////////////////


//
// Big Mess
//

// Ugly recursive category stuff.
function cat_rows( $parent = 0, $level = 0, $categories = 0, $page = 1, $per_page = 20 ) {
	$count = 0;
	_cat_rows($categories, $count, $parent, $level, $page, $per_page);
}

function _cat_rows( $categories, &$count, $parent = 0, $level = 0, $page = 1, $per_page = 20 ) {
	if ( empty($categories) ) {
		$args = array('hide_empty' => 0);
		if ( !empty($_GET['s']) )
		$args['search'] = $_GET['s'];
		$categories = get_categories( $args );
	}

	if ( !$categories )
	return false;

	$children = _get_term_hierarchy('category');

	$start = ($page - 1) * $per_page;
	$end = $start + $per_page;
	$i = -1;
	ob_start();
	foreach ( $categories as $category ) {
		if ( $count >= $end )
		break;

		$i++;

		if ( $category->parent != $parent )
		continue;

		// If the page starts in a subtree, print the parents.
		if ( $count == $start && $category->parent > 0 ) {
			$my_parents = array();
			$my_parent = $category->parent;
			while ( $my_parent) {
				$my_parent = get_category($my_parent);
				$my_parents[] = $my_parent;
				if ( !$my_parent->parent )
				break;
				$my_parent = $my_parent->parent;
			}
			$num_parents = count($my_parents);
			while( $my_parent = array_pop($my_parents) ) {
				echo "\t" . _cat_row( $my_parent, $level - $num_parents );
				$num_parents--;
			}
		}

		if ( $count >= $start )
		echo "\t" . _cat_row( $category, $level );

		unset($categories[$i]); // Prune the working set
		$count++;

		if ( isset($children[$category->term_id]) )
		_cat_rows( $categories, $count, $category->term_id, $level + 1, $page, $per_page );

	}

	$output = ob_get_contents();
	ob_end_clean();

	$output = wpbasic::apply_filters('cat_rows', $output);

	echo $output;
}

function _cat_row( $category, $level, $name_override = false ) {
	global $class;

	$category = get_category( $category );

	$pad = str_repeat( '&#8212; ', $level );
	$name = ( $name_override ? $name_override : $pad . ' ' . $category->name );
	if ( current_user_can( 'manage_categories' ) ) {
		$edit = "<a class='row-title' href='categories.php?action=edit&amp;cat_ID=$category->term_id' title='" . attribute_escape(sprintf(__('Edit "%s"'), $category->name)) . "'>$name</a>";
	} else {
		$edit = $name;
	}

	$class = " class='alternate'" == $class ? '' : " class='alternate'";

	$category->count = number_format_i18n( $category->count );
	$posts_count = ( $category->count > 0 ) ? "<a href='edit.php?cat=$category->term_id'>$category->count</a>" : $category->count;
	$output = "<tr id='cat-$category->term_id'$class>
	<th scope='row' class='check-column'>";
	if ( absint(wpbasic::get_option( 'default_category' ) ) != $category->term_id ) {
		$output .= "<input type='checkbox' name='delete[]' value='$category->term_id' />";
	} else {
		$output .= "&nbsp;";
	}
	$output .= "</th>
	<td>$edit</td>
	<td>$category->description</td>
	<td class='num'>$posts_count</td>\n\t</tr>\n";

	return wpbasic::apply_filters('cat_row', $output);
}

function link_cat_row( $category ) {
	global $class;

	if ( !$category = get_term( $category, 'link_category' ) )
	return false;
	if ( is_wp_error( $category ) )
	return $category;

	$name = ( $name_override ? $name_override : $category->name );
	if ( current_user_can( 'manage_categories' ) ) {
		$edit = "<a class='row-title' href='link-category.php?action=edit&amp;cat_ID=$category->term_id' title='" . attribute_escape(sprintf(__('Edit "%s"'), $category->name)) . "' class='edit'>$name</a>";
		$default_cat_id = (int) wpbasic::get_option( 'default_link_category' );
	} else {
		$edit = $name;
	}

	$class = " class='alternate'" == $class ? '' : " class='alternate'";

	$category->count = number_format_i18n( $category->count );
	$count = ( $category->count > 0 ) ? "<a href='link-manager.php?cat_id=$category->term_id'>$category->count</a>" : $category->count;
	$output = "<tr id='link-cat-$category->term_id'$class>
	<th scope='row' class='check-column'>";
	if ( absint( wpbasic::get_option( 'default_link_category' ) ) != $category->term_id ) {
		$output .= "<input type='checkbox' name='delete[]' value='$category->term_id' />";
	} else {
		$output .= "&nbsp;";
	}
	$output .= "</th>
	<td>$edit</td>
	<td>$category->description</td>
	<td class='num'>$count</td></tr>";

	return wpbasic::apply_filters( 'link_cat_row', $output );
}

function checked( $checked, $current) {
	if( $checked == $current){
		echo ' checked="checked"';
	}
}

function selected( $selected, $current) {
	if( $selected == $current){
		echo ' selected="selected"';
	}
}

//
// Category Checklists
//

// Deprecated. Use wp_link_category_checklist
function dropdown_categories( $default = 0, $parent = 0, $popular_ids = array() ) {
	global $post_ID;
	wp_category_checklist($post_ID);
}

function wp_category_checklist( $post_id = 0, $descendants_and_self = 0, $selected_cats = false, $popular_cats = false ) {
	$walker = new Walker_Category_Checklist;
	$descendants_and_self = (int) $descendants_and_self;

	$args = array();

	if ( is_array( $selected_cats ) )
	$args['selected_cats'] = $selected_cats;
	elseif ( $post_id )
	$args['selected_cats'] = wp_get_post_categories($post_id);
	else
	$args['selected_cats'] = array();

	if ( is_array( $popular_cats ) )
	$args['popular_cats'] = $popular_cats;
	else
	$args['popular_cats'] = get_terms( 'category', array( 'fields' => 'ids', 'orderby' => 'count', 'order' => 'DESC', 'number' => 10, 'hierarchical' => false ) );

	if ( $descendants_and_self ) {
		$categories = get_categories( "child_of=$descendants_and_self&hierarchical=0&hide_empty=0" );
		$self = get_category( $descendants_and_self );
		array_unshift( $categories, $self );
	} else {
		$categories = get_categories('get=all');
	}

	// Post process $categories rather than adding an exclude to the get_terms() query to keep the query the same across all posts (for any query cache)
	$checked_categories = array();
	for ( $i = 0; isset($categories[$i]); $i++ ) {
		if ( in_array($categories[$i]->term_id, $args['selected_cats']) ) {
			$checked_categories[] = $categories[$i];
			unset($categories[$i]);
		}
	}

	// Put checked cats on top
	echo call_user_func_array(array(&$walker, 'walk'), array($checked_categories, 0, $args));
	// Then the rest of them
	echo call_user_func_array(array(&$walker, 'walk'), array($categories, 0, $args));
}

function wp_popular_terms_checklist( $taxonomy, $default = 0, $number = 10, $echo = true ) {
	global $post_ID;
	if ( $post_ID )
	$checked_categories = wp_get_post_categories($post_ID);
	else
	$checked_categories = array();
	$categories = get_terms( $taxonomy, array( 'orderby' => 'count', 'order' => 'DESC', 'number' => $number, 'hierarchical' => false ) );

	$popular_ids = array();
	foreach ( (array) $categories as $category ) {
		$popular_ids[] = $category->term_id;
		if ( !$echo ) // hack for AJAX use
		continue;
		$id = "popular-category-$category->term_id";
		?>

<li id="<?php echo $id; ?>" class="popular-category"><label
	class="selectit" for="in-<?php echo $id; ?>"> <input
	id="in-<?php echo $id; ?>" type="checkbox"
	value="<?php echo (int) $category->term_id; ?>" /> <?php echo wp_specialchars( wpbasic::apply_filters( 'the_category', $category->name ) ); ?>
</label></li>

		<?php
	}
	return $popular_ids;
}

// Deprecated. Use wp_link_category_checklist
function dropdown_link_categories( $default = 0 ) {
	global $link_id;

	wp_link_category_checklist($link_id);
}

function wp_link_category_checklist( $link_id = 0 ) {
	if ( $link_id ) {
		$checked_categories = wp_get_link_cats($link_id);

		if ( count( $checked_categories ) == 0 ) {
			// No selected categories, strange
			$checked_categories[] = $default;
		}
	} else {
		$checked_categories[] = $default;
	}

	$categories = get_terms('link_category', 'orderby=count&hide_empty=0');

	if ( empty($categories) )
	return;

	foreach ( $categories as $category ) {
		$cat_id = $category->term_id;
		$name = wp_specialchars( wpbasic::apply_filters('the_category', $category->name));
		$checked = in_array( $cat_id, $checked_categories );
		echo '<li id="link-category-', $cat_id, '"><label for="in-link-category-', $cat_id, '" class="selectit"><input value="', $cat_id, '" type="checkbox" name="link_category[]" id="in-link-category-', $cat_id, '"', ($checked ? ' checked="checked"' : "" ), '/> ', $name, "</label></li>";
	}
}

// Tag stuff

// Returns a single tag row (see tag_rows below)
// Note: this is also used in admin-ajax.php!
function _tag_row( $tag, $class = '' ) {
	$count = number_format_i18n( $tag->count );
	$count = ( $count > 0 ) ? "<a href='edit.php?tag=$tag->slug'>$count</a>" : $count;

	$name = wpbasic::apply_filters( 'term_name', $tag->name );
	$out = '';
	$out .= '<tr id="tag-' . $tag->term_id . '"' . $class . '>';
	$out .= '<th scope="row" class="check-column"> <input type="checkbox" name="delete_tags[]" value="' . $tag->term_id . '" /></th>';
	$out .= '<td><strong><a class="row-title" href="edit-tags.php?action=edit&amp;tag_ID=' . $tag->term_id . '" title="' . attribute_escape(sprintf(__('Edit "%s"'), $name)) . '">' .
	$name . '</a></td>';

	$out .= "<td class='num'>$count</td>";
	$out .= '</tr>';

	return $out;
}

// Outputs appropriate rows for the Nth page of the Tag Management screen,
// assuming M tags displayed at a time on the page
// Returns the number of tags displayed
function tag_rows( $page = 1, $pagesize = 20, $searchterms = '' ) {

	// Get a page worth of tags
	$start = ($page - 1) * $pagesize;

	$args = array('offset' => $start, 'number' => $pagesize, 'hide_empty' => 0);

	if ( !empty( $searchterms ) ) {
		$args['search'] = $searchterms;
	}

	$tags = get_terms( 'post_tag', $args );

	// convert it to table rows
	$out = '';
	$class = '';
	$count = 0;
	foreach( $tags as $tag )
	$out .= _tag_row( $tag, ++$count % 2 ? ' class="alternate"' : '' );

	// filter and send to screen
	$out = wpbasic::apply_filters('tag_rows', $out);
	echo $out;
	return $count;
}

// define the columns to display, the syntax is 'internal name' => 'display name'
function wp_manage_posts_columns() {
	$posts_columns = array();
	$posts_columns['cb'] = '<input type="checkbox" />';
	if ( 'draft' === $_GET['post_status'] )
	$posts_columns['modified'] = __('Modified');
	elseif ( 'pending' === $_GET['post_status'] )
	$posts_columns['modified'] = __('Submitted');
	else
	$posts_columns['date'] = __('Date');
	$posts_columns['title'] = __('Title');
	$posts_columns['author'] = __('Author');
	$posts_columns['categories'] = __('Categories');
	$posts_columns['tags'] = __('Tags');
	if ( !in_array($_GET['post_status'], array('pending', 'draft', 'future')) )
	$posts_columns['comments'] = '<div class="vers"><img alt="Comments" src="images/comment-grey-bubble.png" /></div>';
	$posts_columns['status'] = __('Status');
	$posts_columns = wpbasic::apply_filters('manage_posts_columns', $posts_columns);

	return $posts_columns;
}

// define the columns to display, the syntax is 'internal name' => 'display name'
function wp_manage_media_columns() {
	$posts_columns = array();
	$posts_columns['cb'] = '<input type="checkbox" />';
	$posts_columns['icon'] = '';
	$posts_columns['media'] = _c('Media|media column header');
	$posts_columns['desc'] = _c('Description|media column header');
	$posts_columns['date'] = _c('Date Added|media column header');
	$posts_columns['parent'] = _c('Appears with|media column header');
	$posts_columns['comments'] = '<div class="vers"><img alt="Comments" src="images/comment-grey-bubble.png" /></div>';
	$posts_columns['location'] = _c('Location|media column header');
	$posts_columns = wpbasic::apply_filters('manage_media_columns', $posts_columns);

	return $posts_columns;
}

function wp_manage_pages_columns() {
	$posts_columns = array();
	$posts_columns['cb'] = '<input type="checkbox" />';
	if ( 'draft' === $_GET['post_status'] )
	$posts_columns['modified'] = __('Modified');
	elseif ( 'pending' === $_GET['post_status'] )
	$posts_columns['modified'] = __('Submitted');
	else
	$posts_columns['date'] = __('Date');
	$posts_columns['title'] = __('Title');
	$posts_columns['author'] = __('Author');
	if ( !in_array($_GET['post_status'], array('pending', 'draft', 'future')) )
	$posts_columns['comments'] = '<div class="vers"><img alt="" src="images/comment-grey-bubble.png" /></div>';
	$posts_columns['status'] = __('Status');
	$posts_columns = wpbasic::apply_filters('manage_pages_columns', $posts_columns);

	return $posts_columns;
}

/*
 * display one row if the page doesn't have any children
 * otherwise, display the row and its children in subsequent rows
 */
function display_page_row( $page, $level = 0 ) {
	global $post;
	static $class;

	$post = $page;
	setup_postdata($page);

	$page->post_title = wp_specialchars( $page->post_title );
	$pad = str_repeat( '&#8212; ', $level );
	$id = (int) $page->ID;
	$class = ('alternate' == $class ) ? '' : 'alternate';
	$posts_columns = wp_manage_pages_columns();
	$title = get_the_title();
	if ( empty($title) )
	$title = __('(no title)');
	?>
<tr id='page-<?php echo $id; ?>' class='<?php echo $class; ?>'>


<?php

foreach ($posts_columns as $column_name=>$column_display_name) {

	switch ($column_name) {

		case 'cb':
			?>
	<th scope="row" class="check-column"><input type="checkbox"
		name="delete[]" value="<?php the_ID(); ?>" /></th>
		<?php
		break;
case 'modified':
case 'date':
	if ( '0000-00-00 00:00:00' == $page->post_date && 'date' == $column_name ) {
		$t_time = $h_time = __('Unpublished');
	} else {
		if ( 'modified' == $column_name ) {
			$t_time = get_the_modified_time(__('Y/m/d g:i:s A'));
			$m_time = $page->post_modified;
			$time = get_post_modified_time('G', true);
		} else {
			$t_time = get_the_time(__('Y/m/d g:i:s A'));
			$m_time = $page->post_date;
			$time = get_post_time('G', true);
		}
		if ( ( abs(time() - $time) ) < 86400 ) {
			if ( ( 'future' == $page->post_status) )
			$h_time = sprintf( __('%s from now'), human_time_diff( $time ) );
			else
			$h_time = sprintf( __('%s ago'), human_time_diff( $time ) );
		} else {
			$h_time = mysql2date(__('Y/m/d'), $m_time);
		}
	}
	?>
	<td><abbr title="<?php echo $t_time ?>"><?php echo $h_time ?></abbr></td>
	<?php
	break;
case 'title':
	?>
	<td><strong><a class="row-title"
		href="page.php?action=edit&amp;post=<?php the_ID(); ?>"
		title="<?php echo attribute_escape(sprintf(__('Edit "%s"'), $title)); ?>"><?php echo $pad; echo $title ?></a></strong>
		<?php if ('private' == $page->post_status) _e(' &#8212; <strong>Private</strong>'); ?></td>
		<?php
		break;

case 'comments':
	?>
	<td class="num">
	<div class="post-com-count-wrapper"><?php
	$left = get_pending_comments_num( $page->ID );
	$pending_phrase = sprintf( __('%s pending'), number_format( $left ) );
	if ( $left )
	echo '<strong>';
	comments_number("<a href='edit-pages.php?page_id=$id' title='$pending_phrase' class='post-com-count'><span class='comment-count'>" . __('0') . '</span></a>', "<a href='edit-pages.php?page_id=$id' title='$pending_phrase' class='post-com-count'><span class='comment-count'>" . __('1') . '</span></a>', "<a href='edit-pages.php?page_id=$id' title='$pending_phrase' class='post-com-count'><span class='comment-count'>" . __('%') . '</span></a>');
	if ( $left )
	echo '</strong>';
	?></div>
	</td>
	<?php
	break;

case 'author':
	?>
	<td><a href="edit-pages.php?author=<?php the_author_ID(); ?>"><?php the_author() ?></a></td>
	<?php
	break;

case 'status':
	?>
	<td><a href="<?php the_permalink(); ?>"
		title="<?php echo attribute_escape(sprintf(__('View "%s"'), $title)); ?>"
		rel="permalink"> <?php
		switch ( $page->post_status ) {
			case 'publish' :
			case 'private' :
				_e('Published');
				break;
			case 'future' :
				_e('Scheduled');
				break;
			case 'pending' :
				_e('Pending Review');
				break;
			case 'draft' :
				_e('Unpublished');
				break;
		}
		?> </a></td>
		<?php
		break;

default:
	?>
	<td><?php wpbasic::do_action('manage_pages_custom_column', $column_name, $id); ?></td>
	<?php
	break;
	}
}
?>

</tr>

<?php
}

/*
 * displays pages in hierarchical order with paging support
 */
function page_rows($pages, $pagenum = 1, $per_page = 20) {
	$level = 0;

	if ( ! $pages ) {
		$pages = get_pages( array('sort_column' => 'menu_order') );

		if ( ! $pages )
		return false;
	}

	/*
	 * arrange pages into two parts: top level pages and children_pages
	 * children_pages is two dimensional array, eg.
	 * children_pages[10][] contains all sub-pages whose parent is 10.
	 * It only takes O(N) to arrange this and it takes O(1) for subsequent lookup operations
	 * If searching, ignore hierarchy and treat everything as top level
	 */
	if ( empty($_GET['s']) )  {

		$top_level_pages = array();
		$children_pages  = array();

		foreach ( $pages as $page ) {

			// catch and repair bad pages
			if ( $page->post_parent == $page->ID ) {
				$page->post_parent = 0;
				$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_parent = '0' WHERE ID = %d", $page->ID) );
				clean_page_cache( $page->ID );
			}

			if ( 0 == $page->post_parent )
			$top_level_pages[] = $page;
			else
			$children_pages[ $page->post_parent ][] = $page;
		}

		$pages = &$top_level_pages;
	}

	$count = 0;
	$start = ($pagenum - 1) * $per_page;
	$end = $start + $per_page;

	foreach ( $pages as $page ) {
		if ( $count >= $end )
		break;

		if ( $count >= $start )
		echo "\t" . display_page_row( $page, $level );

		$count++;

		if ( isset($children_pages) )
		_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page );
	}

	// if it is the last pagenum and there are orphaned pages, display them with paging as well
	if ( isset($children_pages) && $count < $end ){
		foreach( $children_pages as $orphans ){
			foreach ( $orphans as $op ) {
				if ( $count >= $end )
				break;
				if ( $count >= $start )
				echo "\t" . display_page_row( $op, 0 );
				$count++;
			}
		}
	}
}

/*
 * Given a top level page ID, display the nested hierarchy of sub-pages
 * together with paging support
 */
function _page_rows( &$children_pages, &$count, $parent, $level, $pagenum, $per_page ) {

	if ( ! isset( $children_pages[$parent] ) )
	return;

	$start = ($pagenum - 1) * $per_page;
	$end = $start + $per_page;

	foreach ( $children_pages[$parent] as $page ) {

		if ( $count >= $end )
		break;
			
		// If the page starts in a subtree, print the parents.
		if ( $count == $start && $page->post_parent > 0 ) {
			$my_parents = array();
			$my_parent = $page->post_parent;
			while ( $my_parent) {
				$my_parent = get_post($my_parent);
				$my_parents[] = $my_parent;
				if ( !$my_parent->post_parent )
				break;
				$my_parent = $my_parent->post_parent;
			}
			$num_parents = count($my_parents);
			while( $my_parent = array_pop($my_parents) ) {
				echo "\t" . display_page_row( $my_parent, $level - $num_parents );
				$num_parents--;
			}
		}

		if ( $count >= $start )
		echo "\t" . display_page_row( $page, $level );
			
		$count++;

		_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page );
	}

	unset( $children_pages[$parent] ); //required in order to keep track of orphans
}

function user_row( $user_object, $style = '', $role = '' ) {
	global $wp_roles;

	$current_user = wp_get_current_user();

	if ( !( is_object( $user_object) && is_a( $user_object, 'WP_User' ) ) )
	$user_object = new WP_User( (int) $user_object );
	$email = $user_object->user_email;
	$url = $user_object->user_url;
	$short_url = str_replace( 'http://', '', $url );
	$short_url = str_replace( 'www.', '', $short_url );
	if ('/' == substr( $short_url, -1 ))
	$short_url = substr( $short_url, 0, -1 );
	if ( strlen( $short_url ) > 35 )
	$short_url =  substr( $short_url, 0, 32 ).'...';
	$numposts = get_usernumposts( $user_object->ID );
	if ( current_user_can( 'edit_user', $user_object->ID ) ) {
		if ($current_user->ID == $user_object->ID) {
			$edit = 'profile.php';
		} else {
			$edit = clean_url( add_query_arg( 'wp_http_referer', urlencode( clean_url( stripslashes( $_SERVER['REQUEST_URI'] ) ) ), "user-edit.php?user_id=$user_object->ID" ) );
		}
		$edit = "<a href=\"$edit\">$user_object->user_login</a>";
	} else {
		$edit = $user_object->user_login;
	}
	$role_name = $wp_roles->role_names[$role] ? translate_with_context($wp_roles->role_names[$role]) : __('None');
	$r = "<tr id='user-$user_object->ID'$style>
	<th scope='row' class='check-column'><input type='checkbox' name='users[]' id='user_{$user_object->ID}' class='$role' value='{$user_object->ID}' /></th>
	<td><strong>$edit</strong></td>
	<td>$user_object->first_name $user_object->last_name</td>
	<td><a href='mailto:$email' title='" . sprintf( __('e-mail: %s' ), $email ) . "'>$email</a></td>
	<td>$role_name</td>";
	$r .= "\n\t\t<td class='num'>";
	if ( $numposts > 0 ) {
		$r .= "<a href='edit.php?author=$user_object->ID' title='" . __( 'View posts by this author' ) . "' class='edit'>";
		$r .= $numposts;
		$r .= '</a>';
	} else {
		$r .= 0;
	}
	$r .= "</td>\n\t</tr>";
	return $r;
}

function _wp_get_comment_list( $status = '', $s = false, $start, $num ) {
	$wpdb = JWPBlog::getWpdb();

	$start = abs( (int) $start );
	$num = (int) $num;

	if ( 'moderated' == $status )
	$approved = "comment_approved = '0'";
	elseif ( 'approved' == $status )
	$approved = "comment_approved = '1'";
	elseif ( 'spam' == $status )
	$approved = "comment_approved = 'spam'";
	else
	$approved = "( comment_approved = '0' OR comment_approved = '1' )";

	if ( $s ) {
		$s = $wpdb->escape($s);
		$comments = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->comments WHERE
		(comment_author LIKE '%$s%' OR
		comment_author_email LIKE '%$s%' OR
		comment_author_url LIKE ('%$s%') OR
		comment_author_IP LIKE ('%$s%') OR
		comment_content LIKE ('%$s%') ) AND
		$approved
		ORDER BY comment_date_gmt DESC LIMIT $start, $num");
	} else {
		$comments = $wpdb->get_results( "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->comments WHERE $approved ORDER BY comment_date_gmt DESC LIMIT $start, $num" );
	}

	update_comment_cache($comments);

	$total = $wpdb->get_var( "SELECT FOUND_ROWS()" );

	return array($comments, $total);
}

function _wp_comment_row( $comment_id, $mode, $comment_status, $checkbox = true ) {
	global $comment, $post;
	$comment = get_comment( $comment_id );
	$post = get_post($comment->comment_post_ID);
	$authordata = get_userdata($post->post_author);
	$the_comment_status = wp_get_comment_status($comment->comment_ID);
	$class = ('unapproved' == $the_comment_status) ? 'unapproved' : '';

	if ( current_user_can( 'edit_post', $post->ID ) ) {
		$post_link = "<a href='" . get_comment_link() . "'>";

		$post_link .= get_the_title($comment->comment_post_ID) . '</a>';
			
		$edit_link_start = "<a class='row-title' href='comment.php?action=editcomment&amp;c={$comment->comment_ID}' title='" . __('Edit comment') . "'>";
		$edit_link_end = '</a>';
	} else {
		$post_link = get_the_title($comment->comment_post_ID);
		$edit_link_start = $edit_link_end ='';
	}

	$author_url = get_comment_author_url();
	if ( 'http://' == $author_url )
	$author_url = '';
	$author_url_display = $author_url;
	if ( strlen($author_url_display) > 50 )
	$author_url_display = substr($author_url_display, 0, 49) . '...';

	$ptime = date('G', strtotime( $comment->comment_date ) );
	if ( ( abs(time() - $ptime) ) < 86400 )
	$ptime = sprintf( __('%s ago'), human_time_diff( $ptime ) );
	else
	$ptime = mysql2date(__('Y/m/d \a\t g:i A'), $comment->comment_date );

	$delete_url    = clean_url( wp_nonce_url( "comment.php?action=deletecomment&p=$comment->comment_post_ID&c=$comment->comment_ID", "delete-comment_$comment->comment_ID" ) );
	$approve_url   = clean_url( wp_nonce_url( "comment.php?action=approvecomment&p=$comment->comment_post_ID&c=$comment->comment_ID", "approve-comment_$comment->comment_ID" ) );
	$unapprove_url = clean_url( wp_nonce_url( "comment.php?action=unapprovecomment&p=$comment->comment_post_ID&c=$comment->comment_ID", "unapprove-comment_$comment->comment_ID" ) );
	$spam_url      = clean_url( wp_nonce_url( "comment.php?action=deletecomment&dt=spam&p=$comment->comment_post_ID&c=$comment->comment_ID", "delete-comment_$comment->comment_ID" ) );

	?>
<tr id="comment-<?php echo $comment->comment_ID; ?>"
	class='<?php echo $class; ?>'>
	<?php if ( $checkbox ) : ?>
	<td class="check-column"><?php if ( current_user_can('edit_post', $comment->comment_post_ID) ) { ?><input
		type="checkbox" name="delete_comments[]"
		value="<?php echo $comment->comment_ID; ?>" /><?php } ?></td>
		<?php endif; ?>
	<td class="comment">
	<p class="comment-author"><strong><?php echo $edit_link_start; comment_author(); echo $edit_link_end; ?></strong><br />
	<?php if ( !empty($author_url) ) : ?> <a
		href="<?php echo $author_url ?>"><?php echo $author_url_display; ?></a>
	| <?php endif; ?> <?php if ( current_user_can( 'edit_post', $post->ID ) ) : ?>
	<?php if ( !empty($comment->comment_author_email) ): ?> <?php comment_author_email_link() ?>
	| <?php endif; ?> <a
		href="edit-comments.php?s=<?php comment_author_IP() ?>&amp;mode=detail"><?php comment_author_IP() ?></a>
		<?php endif; //current_user_can?></p>
		<?php if ( 'detail' == $mode ) comment_text(); ?>
	<p><?php printf(__('From %1$s, %2$s'), $post_link, $ptime) ?></p>
	</td>
	<td><?php comment_date(__('Y/m/d')); ?></td>
	<td class="action-links"><?php

	$actions = array();

	if ( current_user_can('edit_post', $comment->comment_post_ID) ) {
		$actions['approve']   = "<a href='$approve_url' class='dim:the-comment-list:comment-$comment->comment_ID:unapproved:e7e7d3:e7e7d3:new=approved' title='" . __( 'Approve this comment' ) . "'>" . __( 'Approve' ) . '</a> | ';
		$actions['unapprove'] = "<a href='$unapprove_url' class='dim:the-comment-list:comment-$comment->comment_ID:unapproved:e7e7d3:e7e7d3:new=unapproved' title='" . __( 'Unapprove this comment' ) . "'>" . __( 'Unapprove' ) . '</a> | ';

		// we're looking at list of only approved or only unapproved comments
		if ( 'moderated' == $comment_status ) {
			$actions['approve'] = "<a href='$approve_url' class='delete:the-comment-list:comment-$comment->comment_ID:e7e7d3:action=dim-comment&new=approved' title='" . __( 'Approve this comment' ) . "'>" . __( 'Approve' ) . '</a> | ';
			unset($actions['unapprove']);
		} elseif ( 'approved' == $comment_status ) {
			$actions['unapprove'] = "<a href='$unapprove_url' class='delete:the-comment-list:comment-$comment->comment_ID:e7e7d3:action=dim-comment&new=unapproved' title='" . __( 'Unapprove this comment' ) . "'>" . __( 'Unapprove' ) . '</a> | ';
			unset($actions['approve']);
		}

		$actions['spam']      = "<a href='$spam_url' class='delete:the-comment-list:comment-$comment->comment_ID::spam=1' title='" . __( 'Mark this comment as spam' ) . "'>" . __( 'Spam' ) . '</a> | ';
		$actions['delete']    = "<a href='$delete_url' class='delete:the-comment-list:comment-$comment->comment_ID delete'>" . __('Delete') . '</a>';
		$actions = wpbasic::apply_filters( 'comment_row_actions', $actions, $comment );
		foreach ( $actions as $action => $link )
		echo "<span class='$action'>$link</span>";
	}
	?></td>
</tr>
	<?php
}

function wp_dropdown_cats( $currentcat = 0, $currentparent = 0, $parent = 0, $level = 0, $categories = 0 ) {
	if (!$categories )
	$categories = get_categories( array('hide_empty' => 0) );

	if ( $categories ) {
		foreach ( $categories as $category ) {
			if ( $currentcat != $category->term_id && $parent == $category->parent) {
				$pad = str_repeat( '&#8211; ', $level );
				$category->name = wp_specialchars( $category->name );
				echo "\n\t<option value='$category->term_id'";
				if ( $currentparent == $category->term_id )
				echo " selected='selected'";
				echo ">$pad$category->name</option>";
				wp_dropdown_cats( $currentcat, $currentparent, $category->term_id, $level +1, $categories );
			}
		}
	} else {
		return false;
	}
}

function list_meta( $meta ) {
	// Exit if no meta
	if (!$meta ) {
		echo '<tbody id="the-list" class="list:meta"><tr style="display: none;"><td>&nbsp;</td></tr></tbody>'; //TBODY needed for list-manipulation JS
		return;
	}
	$count = 0;
	?>
<thead>
	<tr>
		<th><?php _e( 'Key' ) ?></th>
		<th><?php _e( 'Value' ) ?></th>
		<th colspan='2'><?php _e( 'Action' ) ?></th>
	</tr>
</thead>
<tbody id='the-list' class='list:meta'>
<?php
foreach ( $meta as $entry )
echo _list_meta_row( $entry, $count );
echo "\n\t</tbody>";
}

function _list_meta_row( $entry, &$count ) {
	static $update_nonce = false;
	if ( !$update_nonce )
	$update_nonce = wp_create_nonce( 'add-meta' );

	$r = '';
	++ $count;
	if ( $count % 2 )
	$style = 'alternate';
	else
	$style = '';
	if ('_' == $entry['meta_key'] { 0 } )
	$style .= ' hidden';

	if ( is_serialized( $entry['meta_value'] ) ) {
		if ( is_serialized_string( $entry['meta_value'] ) ) {
			// this is a serialized string, so we should display it
			$entry['meta_value'] = maybe_unserialize( $entry['meta_value'] );
		} else {
			// this is a serialized array/object so we should NOT display it
			--$count;
			return;
		}
	}

	$entry['meta_key']   = attribute_escape($entry['meta_key']);
	$entry['meta_value'] = htmlspecialchars($entry['meta_value']); // using a <textarea />
	$entry['meta_id'] = (int) $entry['meta_id'];

	$delete_nonce = wp_create_nonce( 'delete-meta_' . $entry['meta_id'] );

	$r .= "\n\t<tr id='meta-{$entry['meta_id']}' class='$style'>";
	$r .= "\n\t\t<td valign='top'><label class='hidden' for='meta[{$entry['meta_id']}][key]'>" . __( 'Key' ) . "</label><input name='meta[{$entry['meta_id']}][key]' id='meta[{$entry['meta_id']}][key]' tabindex='6' type='text' size='20' value='{$entry['meta_key']}' /></td>";
	$r .= "\n\t\t<td><label class='hidden' for='meta[{$entry['meta_id']}][value]'>" . __( 'Value' ) . "</label><textarea name='meta[{$entry['meta_id']}][value]' id='meta[{$entry['meta_id']}][value]' tabindex='6' rows='2' cols='30'>{$entry['meta_value']}</textarea></td>";
	$r .= "\n\t\t<td style='text-align: center;'><input name='updatemeta' type='submit' tabindex='6' value='".attribute_escape(__( 'Update' ))."' class='add:the-list:meta-{$entry['meta_id']}::_ajax_nonce=$update_nonce updatemeta' /><br />";
	$r .= "\n\t\t<input name='deletemeta[{$entry['meta_id']}]' type='submit' ";
	$r .= "class='delete:the-list:meta-{$entry['meta_id']}::_ajax_nonce=$delete_nonce deletemeta' tabindex='6' value='".attribute_escape(__( 'Delete' ))."' />";
	$r .= wp_nonce_field( 'change-meta', '_ajax_nonce', false, false );
	$r .= "</td>\n\t</tr>";
	return $r;
}

function meta_form() {
	$wpdb = JWPBlog::getWpdb();
	$limit = (int) wpbasic::apply_filters( 'postmeta_form_limit', 30 );
	$keys = $wpdb->get_col( "
	SELECT meta_key
	FROM $wpdb->postmeta
	WHERE meta_key NOT LIKE '\_%'
	GROUP BY meta_key
	ORDER BY meta_id DESC
	LIMIT $limit" );
	if ( $keys )
	natcasesort($keys);
	?>
	<p><strong><?php _e( 'Add a new custom field:' ) ?></strong></p>
	<table id="newmeta" cellspacing="3" cellpadding="3">
		<tr>
			<th colspan="2"><label <?php if ( $keys ) : ?> for="metakeyselect"
			<?php else : ?> for="metakeyinput" <?php endif; ?>><?php _e( 'Key' ) ?></label></th>
			<th><label for="metavalue"><?php _e( 'Value' ) ?></label></th>
		</tr>
		<tr valign="top">
			<td style="width: 18%;" class="textright"><?php if ( $keys ) : ?> <select
				id="metakeyselect" name="metakeyselect" tabindex="7">
				<option value="#NONE#"><?php _e( '- Select -' ); ?></option>
				<?php

				foreach ( $keys as $key ) {
					$key = attribute_escape( $key );
					echo "\n\t<option value='$key'>$key</option>";
				}
				?>
			</select> <label for="metakeyinput"><?php _e( 'or' ); ?></label> <?php endif; ?>
			</td>
			<td><input type="text" id="metakeyinput" name="metakeyinput"
				tabindex="7" /></td>
			<td><textarea id="metavalue" name="metavalue" rows="3" cols="25"
				tabindex="8"></textarea></td>
		</tr>
		<tr class="submit">
			<td colspan="3"><?php wp_nonce_field( 'add-meta', '_ajax_nonce', false ); ?>
			<input type="submit" id="addmetasub" name="addmeta"
				class="add:the-list:newmeta" tabindex="9"
				value="<?php _e( 'Add Custom Field' ) ?>" /></td>
		</tr>
	</table>
	<?php

}

function touch_time( $edit = 1, $for_post = 1, $tab_index = 0 ) {
	global $wp_locale, $post, $comment;

	if ( $for_post )
	$edit = ( in_array($post->post_status, array('draft', 'pending') ) && (!$post->post_date || '0000-00-00 00:00:00' == $post->post_date ) ) ? false : true;

	$tab_index_attribute = '';
	if ( (int) $tab_index > 0 )
	$tab_index_attribute = " tabindex=\"$tab_index\"";

	// echo '<label for="timestamp" style="display: block;"><input type="checkbox" class="checkbox" name="edit_date" value="1" id="timestamp"'.$tab_index_attribute.' /> '.__( 'Edit timestamp' ).'</label><br />';

	$time_adj = time() + (wpbasic::get_option( 'gmt_offset' ) * 3600 );
	$post_date = ($for_post) ? $post->post_date : $comment->comment_date;
	$jj = ($edit) ? mysql2date( 'd', $post_date ) : gmdate( 'd', $time_adj );
	$mm = ($edit) ? mysql2date( 'm', $post_date ) : gmdate( 'm', $time_adj );
	$aa = ($edit) ? mysql2date( 'Y', $post_date ) : gmdate( 'Y', $time_adj );
	$hh = ($edit) ? mysql2date( 'H', $post_date ) : gmdate( 'H', $time_adj );
	$mn = ($edit) ? mysql2date( 'i', $post_date ) : gmdate( 'i', $time_adj );
	$ss = ($edit) ? mysql2date( 's', $post_date ) : gmdate( 's', $time_adj );

	$month = "<select id=\"mm\" name=\"mm\"$tab_index_attribute>\n";
	for ( $i = 1; $i < 13; $i = $i +1 ) {
		$month .= "\t\t\t" . '<option value="' . zeroise($i, 2) . '"';
		if ( $i == $mm )
		$month .= ' selected="selected"';
		$month .= '>' . $wp_locale->get_month( $i ) . "</option>\n";
	}
	$month .= '</select>';

	$day = '<input type="text" id="jj" name="jj" value="' . $jj . '" size="2" maxlength="2"' . $tab_index_attribute . ' autocomplete="off"  />';
	$year = '<input type="text" id="aa" name="aa" value="' . $aa . '" size="4" maxlength="5"' . $tab_index_attribute . ' autocomplete="off"  />';
	$hour = '<input type="text" id="hh" name="hh" value="' . $hh . '" size="2" maxlength="2"' . $tab_index_attribute . ' autocomplete="off"  />';
	$minute = '<input type="text" id="mn" name="mn" value="' . $mn . '" size="2" maxlength="2"' . $tab_index_attribute . ' autocomplete="off"  />';
	printf(_c('%1$s%2$s, %3$s <br />@ %4$s : %5$s|1: month input, 2: day input, 3: year input, 4: hour input, 5: minute input'), $month, $day, $year, $hour, $minute);
	echo "\n\n";
	foreach ( array('mm', 'jj', 'aa', 'hh', 'mn') as $timeunit )
	echo '<input type="hidden" id="hidden_' . $timeunit . '" name="hidden_' . $timeunit . '" value="' . $$timeunit . '" />' . "\n";
	?>

	<input type="hidden" id="ss" name="ss" value="<?php echo $ss ?>"
		size="2" maxlength="2" />
		<?php
}

function page_template_dropdown( $default = '' ) {
	$templates = get_page_templates();
	ksort( $templates );
	foreach (array_keys( $templates ) as $template )
	: if ( $default == $templates[$template] )
	$selected = " selected='selected'";
	else
	$selected = '';
	echo "\n\t<option value='".$templates[$template]."' $selected>$template</option>";
	endforeach;
}

function parent_dropdown( $default = 0, $parent = 0, $level = 0 ) {
	global $wpdb, $post_ID;
	$items = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' ORDER BY menu_order", $parent) );

	if ( $items ) {
		foreach ( $items as $item ) {
			// A page cannot be its own parent.
			if (!empty ( $post_ID ) ) {
				if ( $item->ID == $post_ID ) {
					continue;
				}
			}
			$pad = str_repeat( '&nbsp;', $level * 3 );
			if ( $item->ID == $default)
			$current = ' selected="selected"';
			else
			$current = '';

			echo "\n\t<option value='$item->ID'$current>$pad " . wp_specialchars($item->post_title) . "</option>";
			parent_dropdown( $default, $item->ID, $level +1 );
		}
	} else {
		return false;
	}
}

function browse_happy() {
	$getit = __( 'WordPress recommends a better browser' );
	echo '
		<span id="bh" class="alignright"><a href="http://browsehappy.com/" title="'.$getit.'"><img src="images/browse-happy.gif" alt="Browse Happy" /></a></span>
		';
}

/* //TODO: what is this?
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)
add_action( 'in_admin_footer', 'browse_happy' );
*/

function the_attachment_links( $id = false ) {
	$id = (int) $id;
	$post = & get_post( $id );

	if ( $post->post_type != 'attachment' )
	return false;

	$icon = wptemplate::get_attachment_icon( $post->ID );
	$attachment_data = wppost::wp_get_attachment_metadata( $id );
	$thumb = isset( $attachment_data['thumb'] );
	?>
	<form id="the-attachment-links">
	<table>
		<col />
		<col class="widefat" />
		<tr>
			<th scope="row"><?php _e( 'URL' ) ?></th>
			<td><textarea rows="1" cols="40" type="text" class="attachmentlinks"
				readonly="readonly"><?php echo wppost::wp_get_attachment_url(); ?></textarea></td>
		</tr>
		<?php if ( $icon ) : ?>
		<tr>
			<th scope="row"><?php $thumb ? _e( 'Thumbnail linked to file' ) : _e( 'Image linked to file' ); ?></th>
			<td><textarea rows="1" cols="40" type="text" class="attachmentlinks"
				readonly="readonly"><a href="<?php echo wppost::wp_get_attachment_url(); ?>"><?php echo $icon ?></a></textarea></td>
		</tr>
		<tr>
			<th scope="row"><?php $thumb ? _e( 'Thumbnail linked to page' ) : _e( 'Image linked to page' ); ?></th>
			<td><textarea rows="1" cols="40" type="text" class="attachmentlinks"
				readonly="readonly"><a
				href="<?php echo wpadmin::get_attachment_link( $post->ID ) ?>"
				rel="attachment wp-att-<?php echo $post->ID; ?>"><?php echo $icon ?></a></textarea></td>
		</tr>
		<?php else : ?>
		<tr>
			<th scope="row"><?php _e( 'Link to file' ) ?></th>
			<td><textarea rows="1" cols="40" type="text" class="attachmentlinks"
				readonly="readonly"><a href="<?php echo wppost::wp_get_attachment_url(); ?>"
				class="attachmentlink"><?php echo basename( wppost::wp_get_attachment_url() );  ?></a></textarea></td>
		</tr>
		<tr>
			<th scope="row"><?php _e( 'Link to page' ) ?></th>
			<td><textarea rows="1" cols="40" type="text" class="attachmentlinks"
				readonly="readonly"><a
				href="<?php echo wpadmin::get_attachment_link( $post->ID ) ?>"
				rel="attachment wp-att-<?php echo $post->ID ?>"><?php the_title(); ?></a></textarea></td>
		</tr>
		<?php endif; ?>
	</table>
	</form>
	<?php
}

function wp_dropdown_roles( $default = false ) {
	global $wp_roles;
	$r = '';
	foreach( $wp_roles->role_names as $role => $name ) {
		$name = translate_with_context($name);
		if ( $default == $role ) // Make default first in list
		$p = "\n\t<option selected='selected' value='$role'>$name</option>";
		else
		$r .= "\n\t<option value='$role'>$name</option>";
	}
	echo $p . $r;
}

function wp_convert_hr_to_bytes( $size ) {
	$size = strtolower($size);
	$bytes = (int) $size;
	if ( strpos($size, 'k') !== false )
	$bytes = intval($size) * 1024;
	elseif ( strpos($size, 'm') !== false )
	$bytes = intval($size) * 1024 * 1024;
	elseif ( strpos($size, 'g') !== false )
	$bytes = intval($size) * 1024 * 1024 * 1024;
	return $bytes;
}

function wp_convert_bytes_to_hr( $bytes ) {
	$units = array( 0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB' );
	$log = log( $bytes, 1024 );
	$power = (int) $log;
	$size = pow(1024, $log - $power);
	return $size . $units[$power];
}

function wp_max_upload_size() {
	$u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
	$p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
	$bytes = wpbasic::apply_filters( 'upload_size_limit', min($u_bytes, $p_bytes), $u_bytes, $p_bytes );
	return $bytes;
}

function wp_import_upload_form( $action ) {
	$bytes = wpbasic::apply_filters( 'import_upload_size_limit', wp_max_upload_size() );
	$size = wp_convert_bytes_to_hr( $bytes );
	?>
	<form enctype="multipart/form-data" id="import-upload-form"
		method="post" action="<?php echo attribute_escape($action) ?>">
	<p><?php wp_nonce_field('import-upload'); ?> <label for="upload"><?php _e( 'Choose a file from your computer:' ); ?></label>
	(<?php printf( __('Maximum size: %s' ), $size ); ?>) <input type="file"
		id="upload" name="import" size="25" /> <input type="hidden"
		name="action" value="save" /> <input type="hidden"
		name="max_file_size" value="<?php echo $bytes; ?>" /></p>
	<p class="submit"><input type="submit" class="button"
		value="<?php _e( 'Upload file and import' ); ?>" /></p>
	</form>
	<?php
}

function wp_remember_old_slug() {
	global $post;
	$name = attribute_escape($post->post_name); // just in case
	if ( strlen($name) )
	echo '<input type="hidden" id="wp-old-slug" name="wp-old-slug" value="' . $name . '" />';
}

/**
 * add_meta_box() - Add a meta box to an edit form
 *
 * @since 2.5
 *
 * @param string $id String for use in the 'id' attribute of tags.
 * @param string $title Title of the meta box
 * @param string $callback Function that fills the box with the desired content.  The function should echo its output.
 * @param string $page The type of edit page on which to show the box (post, page, link)
 * @param string $context The context within the page where the boxes should show ('normal', 'advanced')
 * @param string $priority The priority within the context where the boxes should show ('high', 'low')
 */
function add_meta_box($id, $title, $callback, $page, $context = 'advanced', $priority = 'default') {
	global $wp_meta_boxes;


	if  ( !isset($wp_meta_boxes) )
	$wp_meta_boxes = array();
	if ( !isset($wp_meta_boxes[$page]) )
	$wp_meta_boxes[$page] = array();
	if ( !isset($wp_meta_boxes[$page][$context]) )
	$wp_meta_boxes[$page][$context] = array();

	foreach ( array('high', 'core', 'default', 'low') as $a_priority ) {
		if ( !isset($wp_meta_boxes[$page][$context][$a_priority][$id]) )
		continue;
		// If a core box was previously added or removed by a plugin, don't add.
		if ( 'core' == $priority ) {
			// If core box previously deleted, don't add
			if ( false === $wp_meta_boxes[$page][$context][$a_priority][$id] )
			return;
			// If box was added with default priority, give it core priority to maintain sort order
			if ( 'default' == $a_priority ) {
				$wp_meta_boxes[$page][$context]['core'][$id] = $wp_meta_boxes[$page][$context]['default'][$id];
				unset($wp_meta_boxes[$page][$context]['default'][$id]);
			}
			return;
		}
		// If no priority given and id already present, use existing priority
		if ( empty($priority) )
		$priority = $a_priority;
		// An id can be in only one priority
		if ( $priority != $a_priority )
		unset($wp_meta_boxes[$page][$context][$a_priority][$id]);
	}

	if ( empty($priority) )
	$priority = low;

	if ( !isset($wp_meta_boxes[$page][$context][$priority]) )
	$wp_meta_boxes[$page][$context][$priority] = array();

	$wp_meta_boxes[$page][$context][$priority][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback);
}

function do_meta_boxes($page, $context, $object) {
	global $wp_meta_boxes;

	wpbasic::do_action('do_meta_boxes', $page, $context, $object);

	if ( !isset($wp_meta_boxes) || !isset($wp_meta_boxes[$page]) || !isset($wp_meta_boxes[$page][$context]) )
	return;

	foreach ( array('high', 'core', 'default', 'low') as $priority ) {
		foreach ( (array) $wp_meta_boxes[$page][$context][$priority] as $box ) {
			if ( false === $box )
			continue;
			echo '<div id="' . $box['id'] . '" class="postbox ' . postbox_classes($box['id'], $page) . '">' . "\n";
			echo "<h3>{$box['title']}</h3>\n";
			echo '<div class="inside">' . "\n";
			call_user_func($box['callback'], $object, $box);
			echo "</div>\n";
			echo "</div>\n";
		}
	}
}

/**
 * remove_meta_box() - Remove a meta box from an edit form
 *
 * @since 2.6
 *
 * @param string $id String for use in the 'id' attribute of tags.
 * @param string $page The type of edit page on which to show the box (post, page, link)
 * @param string $context The context within the page where the boxes should show ('normal', 'advanced')
 */
function remove_meta_box($id, $page, $context) {
	global $wp_meta_boxes;

	if  ( !isset($wp_meta_boxes) )
	$wp_meta_boxes = array();
	if ( !isset($wp_meta_boxes[$page]) )
	$wp_meta_boxes[$page] = array();
	if ( !isset($wp_meta_boxes[$page][$context]) )
	$wp_meta_boxes[$page][$context] = array();

	foreach ( array('high', 'core', 'default', 'low') as $priority )
	$wp_meta_boxes[$page][$context][$priority][$id] = false;
}

///////////////////// theme.php ////////////////////////////

function current_theme_info() {
	$themes = get_themes();
	$current_theme = get_current_theme();
	$ct->name = $current_theme;
	$ct->title = $themes[$current_theme]['Title'];
	$ct->version = $themes[$current_theme]['Version'];
	$ct->parent_theme = $themes[$current_theme]['Parent Theme'];
	$ct->template_dir = $themes[$current_theme]['Template Dir'];
	$ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir'];
	$ct->template = $themes[$current_theme]['Template'];
	$ct->stylesheet = $themes[$current_theme]['Stylesheet'];
	$ct->screenshot = $themes[$current_theme]['Screenshot'];
	$ct->description = $themes[$current_theme]['Description'];
	$ct->author = $themes[$current_theme]['Author'];
	$ct->tags = $themes[$current_theme]['Tags'];
	return $ct;
}

function get_broken_themes(){
	global $wp_broken_themes;
	get_themes();
	return $wp_broken_themes;
}

function get_page_templates() {
	$themes = get_themes();
	$theme = get_current_theme();
	$templates = $themes[$theme]['Template Files'];
	$page_templates = array ();

	if ( is_array( $templates ) ) {
		foreach ( $templates as $template ) {
			$template_data = implode( '', file( WP_CONTENT_DIR.$template ));

			preg_match( '|Template Name:(.*)$|mi', $template_data, $name );
			preg_match( '|Description:(.*)$|mi', $template_data, $description );

			$name = $name[1];
			$description = $description[1];

			if ( !empty( $name ) ) {
				$page_templates[trim( $name )] = basename( $template );
			}
		}
	}

	return $page_templates;
}
/////////////// user.php ////////////////////////

// Creates a new user from the "Users" form using $_POST information.
function add_user() {
	if ( func_num_args() ) { // The hackiest hack that ever did hack
		global $current_user, $wp_roles;
		$user_id = (int) func_get_arg( 0 );

		if ( isset( $_POST['role'] ) ) {
			if( $user_id != $current_user->id || $wp_roles->role_objects[$_POST['role']]->has_cap( 'edit_users' ) ) {
				$user = new WP_User( $user_id );
				$user->set_role( $_POST['role'] );
			}
		}
	} else {
		add_action( 'user_register', 'add_user' ); // See above
		return edit_user();
	}
}

function edit_user( $user_id = 0 ) {
	global $current_user, $wp_roles, $wpdb;
	if ( $user_id != 0 ) {
		$update = true;
		$user->ID = (int) $user_id;
		$userdata = get_userdata( $user_id );
		$user->user_login = $wpdb->escape( $userdata->user_login );
	} else {
		$update = false;
		$user = '';
	}

	if ( isset( $_POST['user_login'] ))
	$user->user_login = wp_specialchars( trim( $_POST['user_login'] ));

	$pass1 = $pass2 = '';
	if ( isset( $_POST['pass1'] ))
	$pass1 = $_POST['pass1'];
	if ( isset( $_POST['pass2'] ))
	$pass2 = $_POST['pass2'];

	if ( isset( $_POST['role'] ) && current_user_can( 'edit_users' ) ) {
		if( $user_id != $current_user->id || $wp_roles->role_objects[$_POST['role']]->has_cap( 'edit_users' ))
		$user->role = $_POST['role'];
	}

	if ( isset( $_POST['email'] ))
	$user->user_email = wp_specialchars( trim( $_POST['email'] ));
	if ( isset( $_POST['url'] ) ) {
		$user->user_url = clean_url( trim( $_POST['url'] ));
		$user->user_url = preg_match('/^(https?|ftps?|mailto|news|irc|gopher|nntp|feed|telnet):/is', $user->user_url) ? $user->user_url : 'http://'.$user->user_url;
	}
	if ( isset( $_POST['first_name'] ))
	$user->first_name = wp_specialchars( trim( $_POST['first_name'] ));
	if ( isset( $_POST['last_name'] ))
	$user->last_name = wp_specialchars( trim( $_POST['last_name'] ));
	if ( isset( $_POST['nickname'] ))
	$user->nickname = wp_specialchars( trim( $_POST['nickname'] ));
	if ( isset( $_POST['display_name'] ))
	$user->display_name = wp_specialchars( trim( $_POST['display_name'] ));
	if ( isset( $_POST['description'] ))
	$user->description = trim( $_POST['description'] );
	if ( isset( $_POST['jabber'] ))
	$user->jabber = wp_specialchars( trim( $_POST['jabber'] ));
	if ( isset( $_POST['aim'] ))
	$user->aim = wp_specialchars( trim( $_POST['aim'] ));
	if ( isset( $_POST['yim'] ))
	$user->yim = wp_specialchars( trim( $_POST['yim'] ));
	if ( !$update )
	$user->rich_editing = 'true';  // Default to true for new users.
	else if ( isset( $_POST['rich_editing'] ) )
	$user->rich_editing = $_POST['rich_editing'];
	else
	$user->rich_editing = 'false';

	if ( !$update )
	$user->admin_color = 'fresh';  // Default to fresh for new users.
	else if ( isset( $_POST['admin_color'] ) )
	$user->admin_color = $_POST['admin_color'];
	else
	$user->admin_color = 'fresh';

	$errors = new WP_Error();

	/* checking that username has been typed */
	if ( $user->user_login == '' )
	$errors->add( 'user_login', __( '<strong>ERROR</strong>: Please enter a username.' ));

	/* checking the password has been typed twice */
	wpbasic::do_action_ref_array( 'check_passwords', array ( $user->user_login, & $pass1, & $pass2 ));

	if ( $update ) {
		if ( empty($pass1) && !empty($pass2) )
		$errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass1' ) );
		elseif ( !empty($pass1) && empty($pass2) )
		$errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass2' ) );
	} else {
		if ( empty($pass1) )
		$errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password.' ), array( 'form-field' => 'pass1' ) );
		elseif ( empty($pass2) )
		$errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password twice.' ), array( 'form-field' => 'pass2' ) );
	}

	/* Check for "\" in password */
	if( strpos( " ".$pass1, "\\" ) )
	$errors->add( 'pass', __( '<strong>ERROR</strong>: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) );

	/* checking the password has been typed twice the same */
	if ( $pass1 != $pass2 )
	$errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter the same password in the two password fields.' ), array( 'form-field' => 'pass1' ) );

	if (!empty ( $pass1 ))
	$user->user_pass = $pass1;

	if ( !$update && !validate_username( $user->user_login ) )
	$errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is invalid. Please enter a valid username.' ));

	if (!$update && username_exists( $user->user_login ))
	$errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ));

	/* checking e-mail address */
	if ( empty ( $user->user_email ) ) {
		$errors->add( 'user_email', __( '<strong>ERROR</strong>: Please enter an e-mail address.' ), array( 'form-field' => 'email' ) );
	} else
	if (!is_email( $user->user_email ) ) {
		$errors->add( 'user_email', __( "<strong>ERROR</strong>: The e-mail address isn't correct." ), array( 'form-field' => 'email' ) );
	}

	if ( $errors->get_error_codes() )
	return $errors;

	if ( $update ) {
		$user_id = wp_update_user( get_object_vars( $user ));
	} else {
		$user_id = wp_insert_user( get_object_vars( $user ));
		wp_new_user_notification( $user_id );
	}
	return $user_id;
}

function get_author_user_ids() {
	$wpdb = JWPBlog::getWpdb();
	$level_key = $wpdb->prefix . 'user_level';
	return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value != '0'", $level_key) );
}

function get_editable_authors( $user_id ) {
	$wpdb = JWPBlog::getWpdb();

	$editable = get_editable_user_ids( $user_id );

	if( !$editable ) {
		return false;
	} else {
		$editable = join(',', $editable);
		$authors = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($editable) ORDER BY display_name" );
	}

	return wpbasic::apply_filters('get_editable_authors', $authors);
}

function get_editable_user_ids( $user_id, $exclude_zeros = true ) {
	$wpdb = JWPBlog::getWpdb();

	$user = new WP_User( $user_id );

	if ( ! $user->has_cap('edit_others_posts') ) {
		if ( $user->has_cap('edit_posts') || $exclude_zeros == false )
		return array($user->id);
		else
		return false;
	}

	$level_key = $wpdb->prefix . 'user_level';

	$query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s", $level_key);
	if ( $exclude_zeros )
	$query .= " AND meta_value != '0'";

	return $wpdb->get_col( $query );
}

function get_nonauthor_user_ids() {
	$wpdb = JWPBlog::getWpdb();
	$level_key = $wpdb->prefix . 'user_level';

	return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = '0'", $level_key) );
}

function get_others_unpublished_posts($user_id, $type='any') {
	$wpdb = JWPBlog::getWpdb();

	$editable = get_editable_user_ids( $user_id );

	if ( in_array($type, array('draft', 'pending')) )
	$type_sql = " post_status = '$type' ";
	else
	$type_sql = " ( post_status = 'draft' OR post_status = 'pending' ) ";

	$dir = ( 'pending' == $type ) ? 'ASC' : 'DESC';

	if( !$editable ) {
		$other_unpubs = '';
	} else {
		$editable = join(',', $editable);
		$other_unpubs = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_title, post_author FROM $wpdb->posts WHERE post_type = 'post' AND $type_sql AND post_author IN ($editable) AND post_author != %d ORDER BY post_modified $dir", $user_id) );
	}

	return wpbasic::apply_filters('get_others_drafts', $other_unpubs);
}

function get_others_drafts($user_id) {
	return get_others_unpublished_posts($user_id, 'draft');
}

function get_others_pending($user_id) {
	return get_others_unpublished_posts($user_id, 'pending');
}

function get_user_to_edit( $user_id ) {
	$user = new WP_User( $user_id );
	$user->user_login   = attribute_escape($user->user_login);
	$user->user_email   = attribute_escape($user->user_email);
	$user->user_url     = clean_url($user->user_url);
	$user->first_name   = attribute_escape($user->first_name);
	$user->last_name    = attribute_escape($user->last_name);
	$user->display_name = attribute_escape($user->display_name);
	$user->nickname     = attribute_escape($user->nickname);
	$user->aim          = attribute_escape($user->aim);
	$user->yim          = attribute_escape($user->yim);
	$user->jabber       = attribute_escape($user->jabber);
	$user->description  =  wp_specialchars($user->description);

	return $user;
}

function get_users_drafts( $user_id ) {
	$wpdb = JWPBlog::getWpdb();
	$query = $wpdb->prepare("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'draft' AND post_author = %d ORDER BY post_modified DESC", $user_id);
	$query = wpbasic::apply_filters('get_users_drafts', $query);
	return $wpdb->get_results( $query );
}

function wp_delete_user($id, $reassign = 'novalue') {
	$wpdb = JWPBlog::getWpdb();

	$id = (int) $id;

	if ($reassign == 'novalue') {
		$post_ids = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id) );

		if ($post_ids) {
			foreach ($post_ids as $post_id)
			wp_delete_post($post_id);
		}

		// Clean links
		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->links WHERE link_owner = %d", $id) );
	} else {
		$reassign = (int) $reassign;
		$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $id) );
		$wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $id) );
	}

	// FINALLY, delete user
	wpbasic::do_action('delete_user', $id);

	$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->users WHERE ID = %d", $id) );
	$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d", $id) );

	wp_cache_delete($id, 'users');
	wp_cache_delete($user->user_login, 'userlogins');
	wp_cache_delete($user->user_email, 'useremail');

	return true;
}

function wp_revoke_user($id) {
	$id = (int) $id;

	$user = new WP_User($id);
	$user->remove_all_caps();
}

/////////////////  registration.php //////////////////////

/**
 * User Registration API
 *
 * @package WordPress
 */

/**
 * username_exists() - Checks whether the given username exists.
 *
 * @since 2.0.0
 *
 * @param string $username Username.
 * @return null|int The user's ID on success, and null on failure.
 */
function username_exists( $username ) {
	if ( $user = get_userdatabylogin( $username ) ) {
		return $user->ID;
	} else {
		return null;
	}
}

/**
 * email_exists() - Checks whether the given email exists.
 *
 * @since 2.1.0
 * @uses $wpdb
 *
 * @param string $email Email.
 * @return bool|int The user's ID on success, and false on failure.
 */
function email_exists( $email ) {
	if ( $user = get_user_by_email($email) )
	return $user->ID;

	return false;
}

/**
 * validate_username() - Checks whether an username is valid.
 *
 * @since 2.0.1
 * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
 *
 * @param string $username Username.
 * @return bool Whether username given is valid
 */
function validate_username( $username ) {
	$sanitized = sanitize_user( $username, true );
	$valid = ( $sanitized == $username );
	return wpbasic::apply_filters( 'validate_username', $valid, $username );
}

/**
 * wp_insert_user() - Insert an user into the database.
 *
 * Can update a current user or insert a new user based on whether
 * the user's ID is present.
 *
 * Can be used to update the user's info (see below), set the user's
 * role, and set the user's preference on whether they want the rich
 * editor on.
 *
 * Most of the $userdata array fields have filters associated with
 * the values. The exceptions are 'rich_editing', 'role', 'jabber',
 * 'aim', 'yim', 'user_registered', and 'ID'. The filters have the
 * prefix 'pre_user_' followed by the field name. An example using
 * 'description' would have the filter called, 'pre_user_description'
 * that can be hooked into.
 *
 * The $userdata array can contain the following fields:
 * 'ID' - An integer that will be used for updating an existing user.
 * 'user_pass' - A string that contains the plain text password for the user.
 * 'user_login' - A string that contains the user's username for logging in.
 * 'user_nicename' - A string that contains a nicer looking name for the user.
 *		The default is the user's username.
 * 'user_url' - A string containing the user's URL for the user's web site.
 * 'user_email' - A string containing the user's email address.
 * 'display_name' - A string that will be shown on the site. Defaults to user's username.
 *		It is likely that you will want to change this, for both appearance and security
 *		through obscurity (that is if you don't use and delete the default 'admin' user).
 * 'nickname' - The user's nickname, defaults to the user's username.
 * 'first_name' - The user's first name.
 * 'last_name' - The user's last name.
 * 'description' - A string containing content about the user.
 * 'rich_editing' - A string for whether to enable the rich editor or not. False if not
 *		empty.
 * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
 * 'role' - A string used to set the user's role.
 * 'jabber' - User's Jabber account.
 * 'aim' - User's AOL IM account.
 * 'yim' - User's Yahoo IM account.
 *
 * @since 2.0.0
 * @uses $wpdb WordPress database layer.
 * @uses apply_filters() Calls filters for most of the $userdata fields with the prefix 'pre_user'. See note above.
 * @uses wpbasic::do_action() Calls 'profile_update' hook when updating giving the user's ID
 * @uses wpbasic::do_action() Calls 'user_register' hook when creating a new user giving the user's ID
 *
 * @param array $userdata An array of user data.
 * @return int The newly created user's ID.
 */
function wp_insert_user($userdata) {
	$wpdb = JWPBlog::getWpdb();

	extract($userdata, EXTR_SKIP);

	// Are we updating or creating?
	if ( !empty($ID) ) {
		$ID = (int) $ID;
		$update = true;
	} else {
		$update = false;
		// Hash the password
		$user_pass = wp_hash_password($user_pass);
	}

	$user_login = sanitize_user($user_login, true);
	$user_login = wpbasic::apply_filters('pre_user_login', $user_login);

	if ( empty($user_nicename) )
	$user_nicename = sanitize_title( $user_login );
	$user_nicename = wpbasic::apply_filters('pre_user_nicename', $user_nicename);

	if ( empty($user_url) )
	$user_url = '';
	$user_url = wpbasic::apply_filters('pre_user_url', $user_url);

	if ( empty($user_email) )
	$user_email = '';
	$user_email = wpbasic::apply_filters('pre_user_email', $user_email);

	if ( empty($display_name) )
	$display_name = $user_login;
	$display_name = wpbasic::apply_filters('pre_user_display_name', $display_name);

	if ( empty($nickname) )
	$nickname = $user_login;
	$nickname = wpbasic::apply_filters('pre_user_nickname', $nickname);

	if ( empty($first_name) )
	$first_name = '';
	$first_name = wpbasic::apply_filters('pre_user_first_name', $first_name);

	if ( empty($last_name) )
	$last_name = '';
	$last_name = wpbasic::apply_filters('pre_user_last_name', $last_name);

	if ( empty($description) )
	$description = '';
	$description = wpbasic::apply_filters('pre_user_description', $description);

	if ( empty($rich_editing) )
	$rich_editing = 'true';

	if ( empty($admin_color) )
	$admin_color = 'fresh';
	$admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color);

	if ( empty($user_registered) )
	$user_registered = gmdate('Y-m-d H:i:s');

	$data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
	$data = stripslashes_deep( $data );

	if ( $update ) {
		$wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
		$user_id = (int) $ID;
	} else {
		$wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
		$user_id = (int) $wpdb->insert_id;
	}

	update_usermeta( $user_id, 'first_name', $first_name);
	update_usermeta( $user_id, 'last_name', $last_name);
	update_usermeta( $user_id, 'nickname', $nickname );
	update_usermeta( $user_id, 'description', $description );
	update_usermeta( $user_id, 'jabber', $jabber );
	update_usermeta( $user_id, 'aim', $aim );
	update_usermeta( $user_id, 'yim', $yim );
	update_usermeta( $user_id, 'rich_editing', $rich_editing);
	update_usermeta( $user_id, 'admin_color', $admin_color);

	if ( $update && isset($role) ) {
		$user = new WP_User($user_id);
		$user->set_role($role);
	}

	if ( !$update ) {
		$user = new WP_User($user_id);
		$user->set_role(wpbasic::get_option('default_role'));
	}

	wp_cache_delete($user_id, 'users');
	wp_cache_delete($user_login, 'userlogins');

	if ( $update )
	wpbasic::do_action('profile_update', $user_id);
	else
	wpbasic::do_action('user_register', $user_id);

	return $user_id;
}

/**
 * wp_update_user() - Update an user in the database
 *
 * It is possible to update a user's password by specifying the
 * 'user_pass' value in the $userdata parameter array.
 *
 * If $userdata does not contain an 'ID' key, then a new user
 * will be created and the new user's ID will be returned.
 *
 * If current user's password is being updated, then the cookies
 * will be cleared.
 *
 * @since 2.0.0
 * @see wp_insert_user() For what fields can be set in $userdata
 * @uses wp_insert_user() Used to update existing user or add new one if user doesn't exist already
 *
 * @param array $userdata An array of user data.
 * @return int The updated user's ID.
 */
function wp_update_user($userdata) {
	$ID = (int) $userdata['ID'];

	// First, get all of the original fields
	$user = get_userdata($ID);

	// Escape data pulled from DB.
	$user = add_magic_quotes(get_object_vars($user));

	// If password is changing, hash it now.
	if ( ! empty($userdata['user_pass']) ) {
		$plaintext_pass = $userdata['user_pass'];
		$userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
	}

	// Merge old and new fields with new fields overwriting old ones.
	$userdata = array_merge($user, $userdata);
	$user_id = wp_insert_user($userdata);

	// Update the cookies if the password changed.
	$current_user = wp_get_current_user();
	if ( $current_user->id == $ID ) {
		if ( isset($plaintext_pass) ) {
			wp_clear_auth_cookie();
			wp_set_auth_cookie($ID);
		}
	}

	return $user_id;
}

/**
 * wp_create_user() - A simpler way of inserting an user into the database.
 *
 * Creates a new user with just the username, password, and email. For a more
 * detail creation of a user, use wp_insert_user() to specify more infomation.
 *
 * @since 2.0.0
 * @see wp_insert_user() More complete way to create a new user
 * @uses $wpdb Escapes $username and $email parameters
 *
 * @param string $username The user's username.
 * @param string $password The user's password.
 * @param string $email The user's email (optional).
 * @return int The new user's ID.
 */
function wp_create_user($username, $password, $email = '') {
	$wpdb = JWPBlog::getWpdb();

	$user_login = $wpdb->escape($username);
	$user_email = $wpdb->escape($email);
	$user_pass = $password;

	$userdata = compact('user_login', 'user_email', 'user_pass');
	return wp_insert_user($userdata);
}

//////////////////////////////////////////////////////////////
////// taxonomly.php ///////

//
// Taxonomy Registration
//

/**
 * Default Taxonomy Objects
 * @since 2.3
 * @global array $wp_taxonomies
 */

/* //TODO: what is this
$wp_taxonomies = array();
$wp_taxonomies['category'] = (object) array('name' => 'category', 'object_type' => 'post', 'hierarchical' => true, 'update_count_callback' => '_update_post_term_count');
$wp_taxonomies['post_tag'] = (object) array('name' => 'post_tag', 'object_type' => 'post', 'hierarchical' => false, 'update_count_callback' => '_update_post_term_count');
$wp_taxonomies['link_category'] = (object) array('name' => 'link_category', 'object_type' => 'link', 'hierarchical' => false);
*/

/**
 * Return all of the taxonomy names that are of $object_type.
 *
 * It appears that this function can be used to find all of the names inside of
 * $wp_taxonomies global variable.
 *
 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
 * result in <code>Array('category', 'post_tag')</code>
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wp_taxonomies
 *
 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
 * @return array The names of all taxonomy of $object_type.
 */
function get_object_taxonomies($object) {
	global $wp_taxonomies;

	if ( is_object($object) ) {
		if ( $object->post_type == 'attachment' )
			return get_attachment_taxonomies($object);
		$object = $object->post_type;
	}

	$object = (array) $object;

	$taxonomies = array();
	foreach ( $wp_taxonomies as $taxonomy ) {
		if ( array_intersect($object, (array) $taxonomy->object_type) )
			$taxonomies[] = $taxonomy->name;
	}

	return $taxonomies;
}

/**
 * Retrieves the taxonomy object of $taxonomy.
 *
 * The get_taxonomy function will first check that the parameter string given
 * is a taxonomy object and if it is, it will return it.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wp_taxonomies
 * @uses is_taxonomy() Checks whether taxonomy exists
 *
 * @param string $taxonomy Name of taxonomy object to return
 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
 */
function get_taxonomy( $taxonomy ) {
	global $wp_taxonomies;

	if ( ! is_taxonomy($taxonomy) )
		return false;

	return $wp_taxonomies[$taxonomy];
}

/**
 * Checks that the taxonomy name exists.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wp_taxonomies
 *
 * @param string $taxonomy Name of taxonomy object
 * @return bool Whether the taxonomy exists or not.
 */
function is_taxonomy( $taxonomy ) {
	global $wp_taxonomies;

	return isset($wp_taxonomies[$taxonomy]);
}

/**
 * Whether the taxonomy object is hierarchical.
 *
 * Checks to make sure that the taxonomy is an object first. Then Gets the
 * object, and finally returns the hierarchical value in the object.
 *
 * A false return value might also mean that the taxonomy does not exist.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses is_taxonomy() Checks whether taxonomy exists
 * @uses get_taxonomy() Used to get the taxonomy object
 *
 * @param string $taxonomy Name of taxonomy object
 * @return bool Whether the taxonomy is hierarchical
 */
function is_taxonomy_hierarchical($taxonomy) {
	if ( ! is_taxonomy($taxonomy) )
		return false;

	$taxonomy = get_taxonomy($taxonomy);
	return $taxonomy->hierarchical;
}

/**
 * Create or modify a taxonomy object. Do not use before init.
 *
 * A simple function for creating or modifying a taxonomy object based on the
 * parameters given. The function will accept an array (third optional
 * parameter), along with strings for the taxonomy name and another string for
 * the object type.
 *
 * Nothing is returned, so expect error maybe or use is_taxonomy() to check
 * whether taxonomy exists.
 *
 * Optional $args contents:
 *
 * hierarachical - has some defined purpose at other parts of the API and is a
 * boolean value.
 *
 * update_count_callback - works much like a hook, in that it will be called
 * when the count is updated.
 *
 * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
 * permastruct; default will use $taxonomy as slug.
 *
 * query_var - false to prevent queries, or string to customize query var
 * (?$query_var=$term); default will use $taxonomy as query var.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wp_taxonomies Inserts new taxonomy object into the list
 * @uses $wp_rewrite Adds rewrite tags and permastructs
 * @uses $wp Adds query vars
 *
 * @param string $taxonomy Name of taxonomy object
 * @param array|string $object_type Name of the object type for the taxonomy object.
 * @param array|string $args See above description for the two keys values.
 */
function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
	global $wp_taxonomies, $wp_rewrite, $wp;

	$defaults = array('hierarchical' => false, 'update_count_callback' => '', 'rewrite' => true, 'query_var' => true);
	$args = wp_parse_args($args, $defaults);

	if ( false !== $args['query_var'] && !empty($wp) ) {
		if ( true === $args['query_var'] )
			$args['query_var'] = $taxonomy;
		$args['query_var'] = sanitize_title_with_dashes($args['query_var']);
		$wp->add_query_var($args['query_var']);
	}

	if ( false !== $args['rewrite'] && !empty($wp_rewrite) ) {
		if ( !is_array($args['rewrite']) )
			$args['rewrite'] = array();
		if ( !isset($args['rewrite']['slug']) )
			$args['rewrite']['slug'] = sanitize_title_with_dashes($taxonomy);
		$wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=$term");
		$wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%");
	}

	$args['name'] = $taxonomy;
	$args['object_type'] = $object_type;
	$wp_taxonomies[$taxonomy] = (object) $args;
}

//
// Term API
//

/**
 * Retrieve object_ids of valid taxonomy and term.
 *
 * The strings of $taxonomies must exist before this function will continue. On
 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
 * still test for the WP_Error class and get the error message.
 *
 * The $terms aren't checked the same as $taxonomies, but still need to exist
 * for $object_ids to be returned.
 *
 * It is possible to change the order that object_ids is returned by either
 * using PHP sort family functions or using the database by using $args with
 * either ASC or DESC array. The value should be in the key named 'order'.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses wp_parse_args() Creates an array from string $args.
 *
 * @param string|array $terms String of term or array of string values of terms that will be used
 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
 * @param array|string $args Change the order of the object_ids, either ASC or DESC
 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
 *	the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
 */
function get_objects_in_term( $terms, $taxonomies, $args = array() ) {
	global $wpdb;

	if ( !is_array( $terms) )
		$terms = array($terms);

	if ( !is_array($taxonomies) )
		$taxonomies = array($taxonomies);

	foreach ( $taxonomies as $taxonomy ) {
		if ( ! is_taxonomy($taxonomy) )
			return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
	}

	$defaults = array('order' => 'ASC');
	$args = wp_parse_args( $args, $defaults );
	extract($args, EXTR_SKIP);

	$order = ( 'desc' == strtolower($order) ) ? 'DESC' : 'ASC';

	$terms = array_map('intval', $terms);

	$taxonomies = "'" . implode("', '", $taxonomies) . "'";
	$terms = "'" . implode("', '", $terms) . "'";

	$object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($terms) ORDER BY tr.object_id $order");

	if ( ! $object_ids )
		return array();

	return $object_ids;
}

/**
 * Get all Term data from database by Term ID.
 *
 * The usage of the get_term function is to apply filters to a term object. It
 * is possible to get a term object from the database before applying the
 * filters.
 *
 * $term ID must be part of $taxonomy, to get from the database. Failure, might
 * be able to be captured by the hooks. Failure would be the same value as $wpdb
 * returns for the get_row method.
 *
 * There are two hooks, one is specifically for each term, named 'get_term', and
 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
 * term object, and the taxonomy name as parameters. Both hooks are expected to
 * return a Term object.
 *
 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
 * Must return term object. Used in get_term() as a catch-all filter for every
 * $term.
 *
 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
 * name. Must return term object. $taxonomy will be the taxonomy name, so for
 * example, if 'category', it would be 'get_category' as the filter name. Useful
 * for custom taxonomies or plugging into default taxonomies.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
 *
 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
 * @param string $taxonomy Taxonomy name that $term is part of.
 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
 * exist then WP_Error will be returned.
 */
function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
	global $wpdb;

	if ( empty($term) )
		return null;

	if ( ! is_taxonomy($taxonomy) )
		return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));

	if ( is_object($term) ) {
		wp_cache_add($term->term_id, $term, $taxonomy);
		$_term = $term;
	} else {
		$term = (int) $term;
		if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
			$_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %s LIMIT 1", $taxonomy, $term) );
			wp_cache_add($term, $_term, $taxonomy);
		}
	}

	$_term = apply_filters('get_term', $_term, $taxonomy);
	$_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
	$_term = sanitize_term($_term, $taxonomy, $filter);

	if ( $output == OBJECT ) {
		return $_term;
	} elseif ( $output == ARRAY_A ) {
		return get_object_vars($_term);
	} elseif ( $output == ARRAY_N ) {
		return array_values(get_object_vars($_term));
	} else {
		return $_term;
	}
}

/**
 * Get all Term data from database by Term field and data.
 *
 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
 * required.
 *
 * The default $field is 'id', therefore it is possible to also use null for
 * field, but not recommended that you do so.
 *
 * If $value does not exist, the return value will be false. If $taxonomy exists
 * and $field and $value combinations exist, the Term will be returned.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
 *
 * @param string $field Either 'slug', 'name', or 'id'
 * @param string|int $value Search for this term value
 * @param string $taxonomy Taxonomy Name
 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
 */
function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
	global $wpdb;

	if ( ! is_taxonomy($taxonomy) )
		return false;

	if ( 'slug' == $field ) {
		$field = 't.slug';
		$value = sanitize_title($value);
		if ( empty($value) )
			return false;
	} else if ( 'name' == $field ) {
		// Assume already escaped
		$field = 't.name';
	} else {
		$field = 't.term_id';
		$value = (int) $value;
	}

	$term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value) );
	if ( !$term )
		return false;

	wp_cache_add($term->term_id, $term, $taxonomy);

	$term = sanitize_term($term, $taxonomy, $filter);

	if ( $output == OBJECT ) {
		return $term;
	} elseif ( $output == ARRAY_A ) {
		return get_object_vars($term);
	} elseif ( $output == ARRAY_N ) {
		return array_values(get_object_vars($term));
	} else {
		return $term;
	}
}

/**
 * Merge all term children into a single array.
 *
 * This recursive function will merge all of the children of $term into the same
 * array. Only useful for taxonomies which are hierarchical.
 *
 * Will return an empty array if $term does not exist in $taxonomy.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses _get_term_hierarchy()
 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
 *
 * @param string $term Name of Term to get children
 * @param string $taxonomy Taxonomy Name
 * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
 */
function get_term_children( $term, $taxonomy ) {
	if ( ! is_taxonomy($taxonomy) )
		return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));

	$terms = _get_term_hierarchy($taxonomy);

	if ( ! isset($terms[$term]) )
		return array();

	$children = $terms[$term];

	foreach ( $terms[$term] as $child ) {
		if ( isset($terms[$child]) )
			$children = array_merge($children, get_term_children($child, $taxonomy));
	}

	return $children;
}

/**
 * Get sanitized Term field.
 *
 * Does checks for $term, based on the $taxonomy. The function is for contextual
 * reasons and for simplicity of usage. See sanitize_term_field() for more
 * information.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
 *
 * @param string $field Term field to fetch
 * @param int $term Term ID
 * @param string $taxonomy Taxonomy Name
 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
 */
function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
	$term = (int) $term;
	$term = get_term( $term, $taxonomy );
	if ( is_wp_error($term) )
		return $term;

	if ( !is_object($term) )
		return '';

	if ( !isset($term->$field) )
		return '';

	return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
}

/**
 * Sanitizes Term for editing.
 *
 * Return value is sanitize_term() and usage is for sanitizing the term for
 * editing. Function is for contextual and simplicity.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses sanitize_term() Passes the return value on success
 *
 * @param int|object $id Term ID or Object
 * @param string $taxonomy Taxonomy Name
 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
 */
function get_term_to_edit( $id, $taxonomy ) {
	$term = get_term( $id, $taxonomy );

	if ( is_wp_error($term) )
		return $term;

	if ( !is_object($term) )
		return '';

	return sanitize_term($term, $taxonomy, 'edit');
}

/**
 * Retrieve the terms in taxonomy or list of taxonomies.
 *
 * You can fully inject any customizations to the query before it is sent, as
 * well as control the output with a filter.
 *
 * The 'get_terms' filter will be called when the cache has the term and will
 * pass the found term along with the array of $taxonomies and array of $args.
 * This filter is also called before the array of terms is passed and will pass
 * the array of terms, along with the $taxonomies and $args.
 *
 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
 * the $args.
 *
 * The list that $args can contain, which will overwrite the defaults.
 *
 * orderby - Default is 'name'. Can be name, count, or nothing (will use
 * term_id).
 *
 * order - Default is ASC. Can use DESC.
 * hide_empty - Default is true. Will not return empty $terms.
 * fields - Default is all.
 * slug - Any terms that has this value. Default is empty string.
 * hierarchical - Whether to return hierarchical taxonomy. Default is true.
 * name__like - Default is empty string.
 *
 * The argument 'pad_counts' will count all of the children along with the
 * $terms.
 *
 * The 'get' argument allows for overwriting 'hide_empty' and 'child_of', which
 * can be done by setting the value to 'all', instead of its default empty
 * string value.
 *
 * The 'child_of' argument will be used if you use multiple taxonomy or the
 * first $taxonomy isn't hierarchical or 'parent' isn't used. The default is 0,
 * which will be translated to a false value. If 'child_of' is set, then
 * 'child_of' value will be tested against $taxonomy to see if 'child_of' is
 * contained within. Will return an empty array if test fails.
 *
 * If 'parent' is set, then it will be used to test against the first taxonomy.
 * Much like 'child_of'. Will return an empty array if the test fails.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
 *
 * @param string|array Taxonomy name or list of Taxonomy names
 * @param string|array $args The values of what to search for when returning terms
 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
 */
function &get_terms($taxonomies, $args = '') {
	global $wpdb;
	$empty_array = array();

	$single_taxonomy = false;
	if ( !is_array($taxonomies) ) {
		$single_taxonomy = true;
		$taxonomies = array($taxonomies);
	}

	foreach ( $taxonomies as $taxonomy ) {
		if ( ! is_taxonomy($taxonomy) )
			return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
	}

	$in_taxonomies = "'" . implode("', '", $taxonomies) . "'";

	$defaults = array('orderby' => 'name', 'order' => 'ASC',
		'hide_empty' => true, 'exclude' => '', 'include' => '',
		'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
		'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
		'pad_counts' => false, 'offset' => '', 'search' => '');
	$args = wp_parse_args( $args, $defaults );
	$args['number'] = absint( $args['number'] );
	$args['offset'] = absint( $args['offset'] );
	if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
		'' != $args['parent'] ) {
		$args['child_of'] = 0;
		$args['hierarchical'] = false;
		$args['pad_counts'] = false;
	}

	if ( 'all' == $args['get'] ) {
		$args['child_of'] = 0;
		$args['hide_empty'] = 0;
		$args['hierarchical'] = false;
		$args['pad_counts'] = false;
	}
	extract($args, EXTR_SKIP);

	if ( $child_of ) {
		$hierarchy = _get_term_hierarchy($taxonomies[0]);
		if ( !isset($hierarchy[$child_of]) )
			return $empty_array;
	}

	if ( $parent ) {
		$hierarchy = _get_term_hierarchy($taxonomies[0]);
		if ( !isset($hierarchy[$parent]) )
			return $empty_array;
	}

	// $args can be whatever, only use the args defined in defaults to compute the key
	$filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
	$key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );

	if ( $cache = wp_cache_get( 'get_terms', 'terms' ) ) {
		if ( isset( $cache[ $key ] ) )
			return apply_filters('get_terms', $cache[$key], $taxonomies, $args);
	}

	if ( 'count' == $orderby )
		$orderby = 'tt.count';
	else if ( 'name' == $orderby )
		$orderby = 't.name';
	else if ( 'slug' == $orderby )
		$orderby = 't.slug';
	else if ( 'term_group' == $orderby )
		$orderby = 't.term_group';
	else
		$orderby = 't.term_id';

	$where = '';
	$inclusions = '';
	if ( !empty($include) ) {
		$exclude = '';
		$interms = preg_split('/[\s,]+/',$include);
		if ( count($interms) ) {
			foreach ( $interms as $interm ) {
				if (empty($inclusions))
					$inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
				else
					$inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
			}
		}
	}

	if ( !empty($inclusions) )
		$inclusions .= ')';
	$where .= $inclusions;

	$exclusions = '';
	if ( !empty($exclude) ) {
		$exterms = preg_split('/[\s,]+/',$exclude);
		if ( count($exterms) ) {
			foreach ( $exterms as $exterm ) {
				if (empty($exclusions))
					$exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
				else
					$exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
			}
		}
	}

	if ( !empty($exclusions) )
		$exclusions .= ')';
	$exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
	$where .= $exclusions;

	if ( !empty($slug) ) {
		$slug = sanitize_title($slug);
		$where .= " AND t.slug = '$slug'";
	}

	if ( !empty($name__like) )
		$where .= " AND t.name LIKE '{$name__like}%'";

	if ( '' != $parent ) {
		$parent = (int) $parent;
		$where .= " AND tt.parent = '$parent'";
	}

	if ( $hide_empty && !$hierarchical )
		$where .= ' AND tt.count > 0';

	if ( !empty($number) ) {
		if( $offset )
			$number = 'LIMIT ' . $offset . ',' . $number;
		else
			$number = 'LIMIT ' . $number;

	} else
		$number = '';

	if ( !empty($search) ) {
		$search = like_escape($search);
		$where .= " AND (t.name LIKE '%$search%')";
	}

	$select_this = '';
	if ( 'all' == $fields )
		$select_this = 't.*, tt.*';
	else if ( 'ids' == $fields )
		$select_this = 't.term_id';
	else if ( 'names' == $fields )
		$select_this = 't.name';

	$query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ($in_taxonomies) $where ORDER BY $orderby $order $number";

	if ( 'all' == $fields ) {
		$terms = $wpdb->get_results($query);
		update_term_cache($terms);
	} else if ( ('ids' == $fields) || ('names' == $fields) ) {
		$terms = $wpdb->get_col($query);
	}

	if ( empty($terms) ) {
		$cache[ $key ] = array();
		wp_cache_set( 'get_terms', $cache, 'terms' );
		return apply_filters('get_terms', array(), $taxonomies, $args);
	}

	if ( $child_of || $hierarchical ) {
		$children = _get_term_hierarchy($taxonomies[0]);
		if ( ! empty($children) )
			$terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
	}

	// Update term counts to include children.
	if ( $pad_counts )
		_pad_term_counts($terms, $taxonomies[0]);

	// Make sure we show empty categories that have children.
	if ( $hierarchical && $hide_empty ) {
		foreach ( $terms as $k => $term ) {
			if ( ! $term->count ) {
				$children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
				foreach ( $children as $child )
					if ( $child->count )
						continue 2;

				// It really is empty
				unset($terms[$k]);
			}
		}
	}
	reset ( $terms );

	$cache[ $key ] = $terms;
	wp_cache_set( 'get_terms', $cache, 'terms' );

	$terms = apply_filters('get_terms', $terms, $taxonomies, $args);
	return $terms;
}

/**
 * Check if Term exists.
 *
 * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 *
 * @param int|string $term The term to check
 * @param string $taxonomy The taxonomy name to use
 * @return mixed Get the term id or Term Object, if exists.
 */
function is_term($term, $taxonomy = '') {
	global $wpdb;

	$select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
	$tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE ";

	if ( is_int($term) ) {
		if ( 0 == $term )
			return 0;
		$where = 't.term_id = %d';
		if ( !empty($taxonomy) )
			return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
		else
			return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
	}

	if ( '' === $slug = sanitize_title($term) )
		return 0;

	$where = 't.slug = %s';
	$else_where = 't.name = %s';

	if ( !empty($taxonomy) ) {
		if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $slug, $taxonomy), ARRAY_A) )
			return $result;
			
		return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $term, $taxonomy), ARRAY_A);
	}

	if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $slug) ) )
		return $result;

	return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $term) );
}

/**
 * Sanitize Term all fields.
 *
 * Relys on sanitize_term_field() to sanitize the term. The difference is that
 * this function will sanitize <strong>all</strong> fields. The context is based
 * on sanitize_term_field().
 *
 * The $term is expected to be either an array or an object.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses sanitize_term_field Used to sanitize all fields in a term
 *
 * @param array|object $term The term to check
 * @param string $taxonomy The taxonomy name to use
 * @param string $context Default is 'display'.
 * @return array|object Term with all fields sanitized
 */
function sanitize_term($term, $taxonomy, $context = 'display') {

	if ( 'raw' == $context )
		return $term;

	$fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');

	$do_object = false;
	if ( is_object($term) )
		$do_object = true;

	foreach ( $fields as $field ) {
		if ( $do_object )
			$term->$field = sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
		else
			$term[$field] = sanitize_term_field($field, $term[$field], $term['term_id'], $taxonomy, $context);
	}

	return $term;
}

/**
 * Cleanse the field value in the term based on the context.
 *
 * Passing a term field value through the function should be assumed to have
 * cleansed the value for whatever context the term field is going to be used.
 *
 * If no context or an unsupported context is given, then default filters will
 * be applied.
 *
 * There are enough filters for each context to support a custom filtering
 * without creating your own filter function. Simply create a function that
 * hooks into the filter you need.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 *
 * @param string $field Term field to sanitize
 * @param string $value Search for this term value
 * @param int $term_id Term ID
 * @param string $taxonomy Taxonomy Name
 * @param string $context Either edit, db, display, attribute, or js.
 * @return mixed sanitized field
 */
function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
	if ( 'parent' == $field  || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
		$value = (int) $value;
		if ( $value < 0 )
			$value = 0;
	}

	if ( 'raw' == $context )
		return $value;

	if ( 'edit' == $context ) {
		$value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy);
		$value = apply_filters("edit_${taxonomy}_$field", $value, $term_id);
		if ( 'description' == $field )
			$value = format_to_edit($value);
		else
			$value = attribute_escape($value);
	} else if ( 'db' == $context ) {
		$value = apply_filters("pre_term_$field", $value, $taxonomy);
		$value = apply_filters("pre_${taxonomy}_$field", $value);
		// Back compat filters
		if ( 'slug' == $field )
			$value = apply_filters('pre_category_nicename', $value);

	} else if ( 'rss' == $context ) {
		$value = apply_filters("term_${field}_rss", $value, $taxonomy);
		$value = apply_filters("${taxonomy}_${field}_rss", $value);
	} else {
		// Use display filters by default.
		$value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context);
		$value = apply_filters("${taxonomy}_$field", $value, $term_id, $context);
	}

	if ( 'attribute' == $context )
		$value = attribute_escape($value);
	else if ( 'js' == $context )
		$value = js_escape($value);

	return $value;
}

/**
 * Count how many terms are in Taxonomy.
 *
 * Default $args is 'ignore_empty' which can be <code>'ignore_empty=true'</code>
 * or <code>array('ignore_empty' => true);</code>.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
 *
 * @param string $taxonomy Taxonomy name
 * @param array|string $args Overwrite defaults
 * @return int How many terms are in $taxonomy
 */
function wp_count_terms( $taxonomy, $args = array() ) {
	global $wpdb;

	$defaults = array('ignore_empty' => false);
	$args = wp_parse_args($args, $defaults);
	extract($args, EXTR_SKIP);

	$where = '';
	if ( $ignore_empty )
		$where = 'AND count > 0';

	return $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE taxonomy = %s $where", $taxonomy) );
}

/**
 * Will unlink the term from the taxonomy.
 *
 * Will remove the term's relationship to the taxonomy, not the term or taxonomy
 * itself. The term and taxonomy will still exist. Will require the term's
 * object ID to perform the operation.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wpdb
 *
 * @param int $object_id The term Object Id that refers to the term
 * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name.
 */
function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
	global $wpdb;

	$object_id = (int) $object_id;

	if ( !is_array($taxonomies) )
		$taxonomies = array($taxonomies);

	foreach ( $taxonomies as $taxonomy ) {
		$terms = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
		$in_terms = "'" . implode("', '", $terms) . "'";
		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_terms)", $object_id) );
		wp_update_term_count($terms, $taxonomy);
	}
}

/**
 * Removes a term from the database.
 *
 * If the term is a parent of other terms, then the children will be updated to
 * that term's parent.
 *
 * The $args 'default' will only override the terms found, if there is only one
 * term found. Any other and the found terms are used.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
 *	hooks, passing term object, term id. 'delete_term' gets an additional
 *	parameter with the $taxonomy parameter.
 *
 * @param int $term Term ID
 * @param string $taxonomy Taxonomy Name
 * @param array|string $args Optional. Change 'default' term id and override found term ids.
 * @return bool|WP_Error Returns false if not term; true if completes delete action.
 */
function wp_delete_term( $term, $taxonomy, $args = array() ) {
	global $wpdb;

	$term = (int) $term;

	if ( ! $ids = is_term($term, $taxonomy) )
		return false;
	if ( is_wp_error( $ids ) )
		return $ids;

	$tt_id = $ids['term_taxonomy_id'];

	$defaults = array();
	$args = wp_parse_args($args, $defaults);
	extract($args, EXTR_SKIP);

	if ( isset($default) ) {
		$default = (int) $default;
		if ( ! is_term($default, $taxonomy) )
			unset($default);
	}

	// Update children to point to new parent
	if ( is_taxonomy_hierarchical($taxonomy) ) {
		$term_obj = get_term($term, $taxonomy);
		if ( is_wp_error( $term_obj ) )
			return $term_obj;
		$parent = $term_obj->parent;

		$wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
	}

	$objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );

	foreach ( (array) $objects as $object ) {
		$terms = wp_get_object_terms($object, $taxonomy, 'fields=ids');
		if ( 1 == count($terms) && isset($default) )
			$terms = array($default);
		else
			$terms = array_diff($terms, array($term));
		$terms = array_map('intval', $terms);
		wp_set_object_terms($object, $terms, $taxonomy);
	}

	$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );

	// Delete the term if no taxonomies use it.
	if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
		$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );

	clean_term_cache($term, $taxonomy);

	do_action('delete_term', $term, $tt_id, $taxonomy);
	do_action("delete_$taxonomy", $term, $tt_id);

	return true;
}

/**
 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
 *
 * The following information has to do the $args parameter and for what can be
 * contained in the string or array of that parameter, if it exists.
 *
 * The first argument is called, 'orderby' and has the default value of 'name'.
 * The other value that is supported is 'count'.
 *
 * The second argument is called, 'order' and has the default value of 'ASC'.
 * The only other value that will be acceptable is 'DESC'.
 *
 * The final argument supported is called, 'fields' and has the default value of
 * 'all'. There are multiple other options that can be used instead. Supported
 * values are as follows: 'all', 'ids', 'names', and finally
 * 'all_with_object_id'.
 *
 * The fields argument also decides what will be returned. If 'all' or
 * 'all_with_object_id' is choosen or the default kept intact, then all matching
 * terms objects will be returned. If either 'ids' or 'names' is used, then an
 * array of all matching term ids or term names will be returned respectively.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wpdb
 *
 * @param int|array $object_id The id of the object(s) to retrieve.
 * @param string|array $taxonomies The taxonomies to retrieve terms from.
 * @param array|string $args Change what is returned
 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
 */
function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
	global $wpdb;

	if ( !is_array($taxonomies) )
		$taxonomies = array($taxonomies);

	foreach ( $taxonomies as $taxonomy ) {
		if ( ! is_taxonomy($taxonomy) )
			return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
	}

	if ( !is_array($object_ids) )
		$object_ids = array($object_ids);
	$object_ids = array_map('intval', $object_ids);

	$defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
	$args = wp_parse_args( $args, $defaults );

	$terms = array();
	if ( count($taxonomies) > 1 ) {
		foreach ( $taxonomies as $index => $taxonomy ) {
			$t = get_taxonomy($taxonomy);
			if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
				unset($taxonomies[$index]);
				$terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
			}
		}
	} else {
		$t = get_taxonomy($taxonomies[0]);
		if ( isset($t->args) && is_array($t->args) )
			$args = array_merge($args, $t->args);
	}

	extract($args, EXTR_SKIP);

	if ( 'count' == $orderby )
		$orderby = 'tt.count';
	else if ( 'name' == $orderby )
		$orderby = 't.name';
	else if ( 'slug' == $orderby )
		$orderby = 't.slug';
	else if ( 'term_group' == $orderby )
		$orderby = 't.term_group';
	else if ( 'term_order' == $orderby )
		$orderby = 'tr.term_order';
	else
		$orderby = 't.term_id';

	$taxonomies = "'" . implode("', '", $taxonomies) . "'";
	$object_ids = implode(', ', $object_ids);

	$select_this = '';
	if ( 'all' == $fields )
		$select_this = 't.*, tt.*';
	else if ( 'ids' == $fields )
		$select_this = 't.term_id';
	else if ( 'names' == $fields )
		$select_this = 't.name';
	else if ( 'all_with_object_id' == $fields )
		$select_this = 't.*, tt.*, tr.object_id';

	$query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) ORDER BY $orderby $order";

	if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
		$terms = array_merge($terms, $wpdb->get_results($query));
		update_term_cache($terms);
	} else if ( 'ids' == $fields || 'names' == $fields ) {
		$terms = array_merge($terms, $wpdb->get_col($query));
	} else if ( 'tt_ids' == $fields ) {
		$terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) ORDER BY tr.term_taxonomy_id $order");
	}

	if ( ! $terms )
		return array();

	return $terms;
}

/**
 * Adds a new term to the database. Optionally marks it as an alias of an existing term.
 *
 * Error handling is assigned for the nonexistance of the $taxonomy and $term
 * parameters before inserting. If both the term id and taxonomy exist
 * previously, then an array will be returned that contains the term id and the
 * contents of what is returned. The keys of the array are 'term_id' and
 * 'term_taxonomy_id' containing numeric values.
 *
 * It is assumed that the term does not yet exist or the above will apply. The
 * term will be first added to the term table and then related to the taxonomy
 * if everything is well. If everything is correct, then several actions will be
 * run prior to a filter and then several actions will be run after the filter
 * is run.
 *
 * The arguments decide how the term is handled based on the $args parameter.
 * The following is a list of the available overrides and the defaults.
 *
 * 'alias_of'. There is no default, but if added, expected is the slug that the
 * term will be an alias of. Expected to be a string.
 *
 * 'description'. There is no default. If exists, will be added to the database
 * along with the term. Expected to be a string.
 *
 * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
 * of 'parent' to the term.
 *
 * 'slug'. Expected to be a string. There is no default.
 *
 * If 'slug' argument exists then the slug will be checked to see if it is not
 * a valid term. If that check succeeds (it is not a valid term), then it is
 * added and the term id is given. If it fails, then a check is made to whether
 * the taxonomy is hierarchical and the parent argument is not empty. If the
 * second check succeeds, the term will be inserted and the term id will be
 * given.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wpdb
 *
 * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
 * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
 * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
 * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
 * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
 *
 * @param int|string $term The term to add or update.
 * @param string $taxonomy The taxonomy to which to add the term
 * @param array|string $args Change the values of the inserted term
 * @return array|WP_Error The Term ID and Term Taxonomy ID
 */
function wp_insert_term( $term, $taxonomy, $args = array() ) {
	global $wpdb;

	if ( ! is_taxonomy($taxonomy) )
		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));

	if ( is_int($term) && 0 == $term )
		return new WP_Error('invalid_term_id', __('Invalid term ID'));

	if ( '' == trim($term) )
		return new WP_Error('empty_term_name', __('A name is required for this term'));

	$defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
	$args = wp_parse_args($args, $defaults);
	$args['name'] = $term;
	$args['taxonomy'] = $taxonomy;
	$args = sanitize_term($args, $taxonomy, 'db');
	extract($args, EXTR_SKIP);

	// expected_slashed ($name)
	$name = stripslashes($name);
	$description = stripslashes($description);

	if ( empty($slug) )
		$slug = sanitize_title($name);

	$term_group = 0;
	if ( $alias_of ) {
		$alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
		if ( $alias->term_group ) {
			// The alias we want is already in a group, so let's use that one.
			$term_group = $alias->term_group;
		} else {
			// The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
			$term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
			$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $alias->term_id ) );
		}
	}

	if ( ! $term_id = is_term($slug) ) {
		if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
			return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
		$term_id = (int) $wpdb->insert_id;
	} else if ( is_taxonomy_hierarchical($taxonomy) && !empty($parent) ) {
		// If the taxonomy supports hierarchy and the term has a parent, make the slug unique
		// by incorporating parent slugs.
		$slug = wp_unique_term_slug($slug, (object) $args);
		if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
			return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
		$term_id = (int) $wpdb->insert_id;
	}

	if ( empty($slug) ) {
		$slug = sanitize_title($slug, $term_id);
		$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
	}

	$tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );

	if ( !empty($tt_id) )
		return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);

	$wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
	$tt_id = (int) $wpdb->insert_id;

	do_action("create_term", $term_id, $tt_id);
	do_action("create_$taxonomy", $term_id, $tt_id);

	$term_id = apply_filters('term_id_filter', $term_id, $tt_id);

	clean_term_cache($term_id, $taxonomy);

	do_action("created_term", $term_id, $tt_id);
	do_action("created_$taxonomy", $term_id, $tt_id);

	return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
}

/**
 * Create Term and Taxonomy Relationships.
 *
 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
 * term and taxonomy relationship if it doesn't already exist. Creates a term if
 * it doesn't exist (using the slug).
 *
 * A relationship means that the term is grouped in or belongs to the taxonomy.
 * A term has no meaning until it is given context by defining which taxonomy it
 * exists under.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wpdb
 *
 * @param int $object_id The object to relate to.
 * @param array|int|string $term The slug or id of the term.
 * @param array|string $taxonomy The context in which to relate the term to the object.
 * @param bool $append If false will delete difference of terms.
 * @return array|WP_Error Affected Term IDs
 */
function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
	global $wpdb;

	$object_id = (int) $object_id;

	if ( ! is_taxonomy($taxonomy) )
		return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));

	if ( !is_array($terms) )
		$terms = array($terms);

	if ( ! $append )
		$old_terms =  wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');

	$tt_ids = array();
	$term_ids = array();

	foreach ($terms as $term) {
		if ( !strlen(trim($term)) )
			continue;

		if ( !$id = is_term($term, $taxonomy) )
			$id = wp_insert_term($term, $taxonomy);
		if ( is_wp_error($id) )
			return $id;
		$term_ids[] = $id['term_id'];
		$id = $id['term_taxonomy_id'];
		$tt_ids[] = $id;

		if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $id ) ) )
			continue;
		$wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $id ) );
	}

	wp_update_term_count($tt_ids, $taxonomy);

	if ( ! $append ) {
		$delete_terms = array_diff($old_terms, $tt_ids);
		if ( $delete_terms ) {
			$in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
			$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
			wp_update_term_count($delete_terms, $taxonomy);
		}
	}

	$t = get_taxonomy($taxonomy);
	if ( ! $append && isset($t->sort) && $t->sort ) {
		$values = array();
		$term_order = 0;
		$final_tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
		foreach ( $tt_ids as $tt_id )
			if ( in_array($tt_id, $final_tt_ids) )
				$values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
		if ( $values )
			$wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
	}

	return $tt_ids;
}

/**
 * Will make slug unique, if it isn't already.
 *
 * The $slug has to be unique global to every taxonomy, meaning that one
 * taxonomy term can't have a matching slug with another taxonomy term. Each
 * slug has to be globally unique for every taxonomy.
 *
 * The way this works is that if the taxonomy that the term belongs to is
 * heirarchical and has a parent, it will append that parent to the $slug.
 *
 * If that still doesn't return an unique slug, then it try to append a number
 * until it finds a number that is truely unique.
 *
 * The only purpose for $term is for appending a parent, if one exists.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wpdb
 *
 * @param string $slug The string that will be tried for a unique slug
 * @param object $term The term object that the $slug will belong too
 * @return string Will return a true unique slug.
 */
function wp_unique_term_slug($slug, $term) {
	global $wpdb;

	// If the taxonomy supports hierarchy and the term has a parent, make the slug unique
	// by incorporating parent slugs.
	if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
		$the_parent = $term->parent;
		while ( ! empty($the_parent) ) {
			$parent_term = get_term($the_parent, $term->taxonomy);
			if ( is_wp_error($parent_term) || empty($parent_term) )
				break;
				$slug .= '-' . $parent_term->slug;
			if ( empty($parent_term->parent) )
				break;
			$the_parent = $parent_term->parent;
		}
	}

	// If we didn't get a unique slug, try appending a number to make it unique.
	if ( !empty($args['term_id']) )
		$query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
	else
		$query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );

	if ( $wpdb->get_var( $query ) ) {
		$num = 2;
		do {
			$alt_slug = $slug . "-$num";
			$num++;
			$slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
		} while ( $slug_check );
		$slug = $alt_slug;
	}

	return $slug;
}

/**
 * Update term based on arguments provided.
 *
 * The $args will indiscriminately override all values with the same field name.
 * Care must be taken to not override important information need to update or
 * update will fail (or perhaps create a new term, neither would be acceptable).
 *
 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
 * defined in $args already.
 *
 * 'alias_of' will create a term group, if it doesn't already exist, and update
 * it for the $term.
 *
 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
 * used. It should also be noted that if you set 'slug' and it isn't unique then
 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
 * will be created for you.
 *
 * For what can be overrode in $args, check the term scheme can contain and stay
 * away from the term keys.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses $wpdb
 * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
 * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
 *	id and taxonomy id.
 *
 * @param int $term The ID of the term
 * @param string $taxonomy The context in which to relate the term to the object.
 * @param array|string $args Overwrite term field values
 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
 */
function wp_update_term( $term, $taxonomy, $args = array() ) {
	global $wpdb;

	if ( ! is_taxonomy($taxonomy) )
		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));

	$term_id = (int) $term;

	// First, get all of the original args
	$term = get_term ($term_id, $taxonomy, ARRAY_A);

	// Escape data pulled from DB.
	$term = add_magic_quotes($term);

	// Merge old and new args with new args overwriting old ones.
	$args = array_merge($term, $args);

	$defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
	$args = wp_parse_args($args, $defaults);
	$args = sanitize_term($args, $taxonomy, 'db');
	extract($args, EXTR_SKIP);

	// expected_slashed ($name)
	$name = stripslashes($name);
	$description = stripslashes($description);

	if ( '' == trim($name) )
		return new WP_Error('empty_term_name', __('A name is required for this term'));

	$empty_slug = false;
	if ( empty($slug) ) {
		$empty_slug = true;
		$slug = sanitize_title($name);
	}

	if ( $alias_of ) {
		$alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
		if ( $alias->term_group ) {
			// The alias we want is already in a group, so let's use that one.
			$term_group = $alias->term_group;
		} else {
			// The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
			$term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
			$wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
		}
	}

	// Check for duplicate slug
	$id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
	if ( $id && ($id != $term_id) ) {
		// If an empty slug was passed or the parent changed, reset the slug to something unique.
		// Otherwise, bail.
		if ( $empty_slug || ( $parent != $term->parent) )
			$slug = wp_unique_term_slug($slug, (object) $args);
		else
			return new WP_Error('duplicate_term_slug', sprintf(__('The slug "%s" is already in use by another term'), $slug));
	}

	$wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );

	if ( empty($slug) ) {
		$slug = sanitize_title($name, $term_id);
		$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
	}

	$tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) );

	$wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );

	do_action("edit_term", $term_id, $tt_id);
	do_action("edit_$taxonomy", $term_id, $tt_id);

	$term_id = apply_filters('term_id_filter', $term_id, $tt_id);

	clean_term_cache($term_id, $taxonomy);

	do_action("edited_term", $term_id, $tt_id);
	do_action("edited_$taxonomy", $term_id, $tt_id);

	return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
}

/**
 * Enable or disable term counting.
 *
 * @since 2.6
 *
 * @param bool $defer Optional.
 * @return bool
 */
function wp_defer_term_counting($defer=NULL) {
	static $_defer = false;

	if ( is_bool($defer) ) {
		$_defer = $defer;
		// flush any deferred counts
		if ( !$defer )
			wp_update_term_count( NULL, NULL, true );
	}

	return $_defer;
}

/**
 * Updates the amount of terms in taxonomy.
 *
 * If there is a taxonomy callback applyed, then it will be called for updating
 * the count.
 *
 * The default action is to count what the amount of terms have the relationship
 * of term ID. Once that is done, then update the database.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wpdb
 *
 * @param int|array $terms The ID of the terms
 * @param string $taxonomy The context of the term.
 * @return bool If no terms will return false, and if successful will return true.
 */
function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
	static $_deferred = array();

	if ( $do_deferred ) {
		foreach ( array_keys($_deferred) as $tax ) {
			wp_update_term_count_now( $_deferred[$tax], $tax );
			unset( $_deferred[$tax] );
		}
	}

	if ( empty($terms) )
		return false;

	if ( !is_array($terms) )
		$terms = array($terms);

	if ( wp_defer_term_counting() ) {
		if ( !isset($_deferred[$taxonomy]) )
			$_deferred[$taxonomy] = array();
		$_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
		return true;
	}

	return wp_update_term_count_now( $terms, $taxonomy );
}

/**
 * Perform term count update immediately.
 *
 * @since 2.6
 *
 * @param array $terms IDs of Terms to update.
 * @param string $taxonomy The context of the term.
 * @return bool Always true when complete.
 */
function wp_update_term_count_now( $terms, $taxonomy ) {
	global $wpdb;

	$terms = array_map('intval', $terms);

	$taxonomy = get_taxonomy($taxonomy);
	if ( !empty($taxonomy->update_count_callback) ) {
		call_user_func($taxonomy->update_count_callback, $terms);
	} else {
		// Default count updater
		foreach ($terms as $term) {
			$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
			$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
		}

	}

	clean_term_cache($terms);

	return true;
}

//
// Cache
//


/**
 * Removes the taxonomy relationship to terms from the cache.
 *
 * Will remove the entire taxonomy relationship containing term $object_id. The
 * term IDs have to exist within the taxonomy $object_type for the deletion to
 * take place.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @see get_object_taxonomies() for more on $object_type
 * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
 *	Passes, function params in same order.
 *
 * @param int|array $object_ids Single or list of term object ID(s)
 * @param array|string $object_type The taxonomy object type
 */
function clean_object_term_cache($object_ids, $object_type) {
	if ( !is_array($object_ids) )
		$object_ids = array($object_ids);

	foreach ( $object_ids as $id )
		foreach ( get_object_taxonomies($object_type) as $taxonomy )
			wp_cache_delete($id, "{$taxonomy}_relationships");

	do_action('clean_object_term_cache', $object_ids, $object_type);
}


/**
 * Will remove all of the term ids from the cache.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses $wpdb
 *
 * @param int|array $ids Single or list of Term IDs
 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
 */
function clean_term_cache($ids, $taxonomy = '') {
	global $wpdb;

	if ( !is_array($ids) )
		$ids = array($ids);

	$taxonomies = array();
	// If no taxonomy, assume tt_ids.
	if ( empty($taxonomy) ) {
		$tt_ids = implode(', ', $ids);
		$terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
		foreach ( (array) $terms as $term ) {
			$taxonomies[] = $term->taxonomy;
			wp_cache_delete($term->term_id, $term->taxonomy);
		}
		$taxonomies = array_unique($taxonomies);
	} else {
		foreach ( $ids as $id ) {
			wp_cache_delete($id, $taxonomy);
		}
		$taxonomies = array($taxonomy);
	}

	foreach ( $taxonomies as $taxonomy ) {
		wp_cache_delete('all_ids', $taxonomy);
		wp_cache_delete('get', $taxonomy);
		delete_option("{$taxonomy}_children");
	}

	wp_cache_delete('get_terms', 'terms');

	do_action('clean_term_cache', $ids, $taxonomy);
}


/**
 * Retrieves the taxonomy relationship to the term object id.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
 *
 * @param int|array $id Term object ID
 * @param string $taxonomy Taxonomy Name
 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
 */
function &get_object_term_cache($id, $taxonomy) {
	$cache = wp_cache_get($id, "{$taxonomy}_relationships");
	return $cache;
}


/**
 * Updates the cache for Term ID(s).
 *
 * Will only update the cache for terms not already cached.
 *
 * The $object_ids expects that the ids be separated by commas, if it is a
 * string.
 *
 * It should be noted that update_object_term_cache() is very time extensive. It
 * is advised that the function is not called very often or at least not for a
 * lot of terms that exist in a lot of taxonomies. The amount of time increases
 * for each term and it also increases for each taxonomy the term belongs to.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 * @uses wp_get_object_terms() Used to get terms from the database to update
 *
 * @param string|array $object_ids Single or list of term object ID(s)
 * @param array|string $object_type The taxonomy object type
 * @return null|bool Null value is given with empty $object_ids. False if
 */
function update_object_term_cache($object_ids, $object_type) {
	if ( empty($object_ids) )
		return;

	if ( !is_array($object_ids) )
		$object_ids = explode(',', $object_ids);

	$object_ids = array_map('intval', $object_ids);

	$taxonomies = get_object_taxonomies($object_type);

	$ids = array();
	foreach ( (array) $object_ids as $id ) {
		foreach ( $taxonomies as $taxonomy ) {
			if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
				$ids[] = $id;
				break;
			}
		}
	}

	if ( empty( $ids ) )
		return false;

	$terms = wp_get_object_terms($ids, $taxonomies, 'fields=all_with_object_id');

	$object_terms = array();
	foreach ( (array) $terms as $term )
		$object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;

	foreach ( $ids as $id ) {
		foreach ( $taxonomies  as $taxonomy ) {
			if ( ! isset($object_terms[$id][$taxonomy]) ) {
				if ( !isset($object_terms[$id]) )
					$object_terms[$id] = array();
				$object_terms[$id][$taxonomy] = array();
			}
		}
	}

	foreach ( $object_terms as $id => $value ) {
		foreach ( $value as $taxonomy => $terms ) {
			wp_cache_set($id, $terms, "{$taxonomy}_relationships");
		}
	}
}


/**
 * Updates Terms to Taxonomy in cache.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.3
 *
 * @param array $terms List of Term objects to change
 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
 */
function update_term_cache($terms, $taxonomy = '') {
	foreach ( $terms as $term ) {
		$term_taxonomy = $taxonomy;
		if ( empty($term_taxonomy) )
			$term_taxonomy = $term->taxonomy;

		wp_cache_add($term->term_id, $term, $term_taxonomy);
	}
}

//
// Private
//


/**
 * Retrieves children of taxonomy.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @access private
 * @since 2.3
 *
 * @uses update_option() Stores all of the children in "$taxonomy_children"
 *	 option. That is the name of the taxonomy, immediately followed by '_children'.
 *
 * @param string $taxonomy Taxonomy Name
 * @return array Empty if $taxonomy isn't hierarachical or returns children.
 */
function _get_term_hierarchy($taxonomy) {
	if ( !is_taxonomy_hierarchical($taxonomy) )
		return array();
	$children = get_option("{$taxonomy}_children");
	if ( is_array($children) )
		return $children;

	$children = array();
	$terms = get_terms($taxonomy, 'get=all');
	foreach ( $terms as $term ) {
		if ( $term->parent > 0 )
			$children[$term->parent][] = $term->term_id;
	}
	update_option("{$taxonomy}_children", $children);

	return $children;
}


/**
 * Get array of child terms.
 *
 * If $terms is an array of objects, then objects will returned from the
 * function. If $terms is an array of IDs, then an array of ids of children will
 * be returned.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @access private
 * @since 2.3
 *
 * @param int $term_id Look for this Term ID in $terms
 * @param array $terms List of Term IDs
 * @param string $taxonomy Term Context
 * @return array Empty if $terms is empty else returns full list of child terms.
 */
function &_get_term_children($term_id, $terms, $taxonomy) {
	$empty_array = array();
	if ( empty($terms) )
		return $empty_array;

	$term_list = array();
	$has_children = _get_term_hierarchy($taxonomy);

	if  ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
		return $empty_array;

	foreach ( $terms as $term ) {
		$use_id = false;
		if ( !is_object($term) ) {
			$term = get_term($term, $taxonomy);
			if ( is_wp_error( $term ) )
				return $term;
			$use_id = true;
		}

		if ( $term->term_id == $term_id )
			continue;

		if ( $term->parent == $term_id ) {
			if ( $use_id )
				$term_list[] = $term->term_id;
			else
				$term_list[] = $term;

			if ( !isset($has_children[$term->term_id]) )
				continue;

			if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
				$term_list = array_merge($term_list, $children);
		}
	}

	return $term_list;
}


/**
 * Add count of children to parent count.
 *
 * Recalculates term counts by including items from child terms. Assumes all
 * relevant children are already in the $terms argument.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @access private
 * @since 2.3
 * @uses $wpdb
 *
 * @param array $terms List of Term IDs
 * @param string $taxonomy Term Context
 * @return null Will break from function if conditions are not met.
 */
function _pad_term_counts(&$terms, $taxonomy) {
	global $wpdb;

	// This function only works for post categories.
	if ( 'category' != $taxonomy )
		return;

	$term_hier = _get_term_hierarchy($taxonomy);

	if ( empty($term_hier) )
		return;

	$term_items = array();

	foreach ( $terms as $key => $term ) {
		$terms_by_id[$term->term_id] = & $terms[$key];
		$term_ids[$term->term_taxonomy_id] = $term->term_id;
	}

	// Get the object and term ids and stick them in a lookup table
	$results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (".join(',', array_keys($term_ids)).") AND post_type = 'post' AND post_status = 'publish'");
	foreach ( $results as $row ) {
		$id = $term_ids[$row->term_taxonomy_id];
		++$term_items[$id][$row->object_id];
	}

	// Touch every ancestor's lookup row for each post in each term
	foreach ( $term_ids as $term_id ) {
		$child = $term_id;
		while ( $parent = $terms_by_id[$child]->parent ) {
			if ( !empty($term_items[$term_id]) )
				foreach ( $term_items[$term_id] as $item_id => $touches )
					++$term_items[$parent][$item_id];
			$child = $parent;
		}
	}

	// Transfer the touched cells
	foreach ( (array) $term_items as $id => $items )
		if ( isset($terms_by_id[$id]) )
			$terms_by_id[$id]->count = count($items);
}

//
// Default callbacks
//

/**
 * Will update term count based on posts.
 *
 * Private function for the default callback for post_tag and category
 * taxonomies.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @access private
 * @since 2.3
 * @uses $wpdb
 *
 * @param array $terms List of Term IDs
 */
function _update_post_term_count( $terms ) {
	global $wpdb;

	foreach ( $terms as $term ) {
		$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term ) );
		$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
	}
}


/**
 * Generates a permalink for a taxonomy term archive.
 *
 * @since 2.6
 *
 * @param object|int|string $term
 * @param string $taxonomy
 * @return string HTML link to taxonomy term archive
 */
function get_term_link( $term, $taxonomy ) {
	global $wp_rewrite;

	// use legacy functions for core taxonomies until they are fully plugged in
	if ( $taxonomy == 'category' )
		return get_category_link($term);
	if ( $taxonomy == 'post_tag' )
		return get_tag_link($term);

	$termlink = $wp_rewrite->get_extra_permastruct($taxonomy);

	if ( !is_object($term) ) {
		if ( is_int($term) ) {
			$term = &get_term($term, $taxonomy);
		} else {
			$term = &get_term_by('slug', $term, $taxonomy);
		}
	}
	if ( is_wp_error( $term ) )
		return $term;

	$slug = $term->slug;

	if ( empty($termlink) ) {
		$file = get_option('home') . '/';
		$t = get_taxonomy($taxonomy);
		if ( $t->query_var )
			$termlink = "$file?$t->query_var=$slug";
		else
			$termlink = "$file?taxonomy=$taxonomy&term=$slug";
	} else {
		$termlink = str_replace("%$taxonomy%", $slug, $termlink);
		$termlink = get_option('home') . user_trailingslashit($termlink, 'category');
	}
	return apply_filters('term_link', $termlink, $term, $taxonomy);
}

/**
 * Display the taxonomies of a post with available options.
 *
 * This function can be used within the loop to display the taxonomies for a
 * post without specifying the Post ID. You can also use it outside the Loop to
 * display the taxonomies for a specific post.
 *
 * The available defaults are:
 * 'post' : default is 0. The post ID to get taxonomies of.
 * 'before' : default is empty string. Display before taxonomies list.
 * 'sep' : default is empty string. Separate every taxonomy with value in this.
 * 'after' : default is empty string. Display this after the taxonomies list.
 *
 * @since 2.6
 * @uses get_the_taxonomies()
 *
 * @param array $args Override the defaults.
 */
function the_taxonomies($args = array()) {
	$defaults = array(
		'post' => 0,
		'before' => '',
		'sep' => ' ',
		'after' => '',
	);

	$r = wp_parse_args( $args, $defaults );
	extract( $r, EXTR_SKIP );

	echo $before . join($sep, get_the_taxonomies($post)) . $after;
}

/**
 * Retrieve all taxonomies associated with a post.
 *
 * This function can be used within the loop. It will also return an array of
 * the taxonomies with links to the taxonomy and name.
 *
 * @since 2.6
 *
 * @param int $post Optional. Post ID or will use Global Post ID (in loop).
 * @return array
 */
function get_the_taxonomies($post = 0) {
	if ( is_int($post) )
		$post =& get_post($post);
	elseif ( !is_object($post) )
		$post =& $GLOBALS['post'];

	$taxonomies = array();

	if ( !$post )
		return $taxonomies;

	$template = apply_filters('taxonomy_template', '%s: %l.');

	foreach ( get_object_taxonomies($post) as $taxonomy ) {
		$t = (array) get_taxonomy($taxonomy);
		if ( empty($t['label']) )
			$t['label'] = $taxonomy;
		if ( empty($t['args']) )
			$t['args'] = array();
		if ( empty($t['template']) )
			$t['template'] = $template;

		$terms = get_object_term_cache($post->ID, $taxonomy);
		if ( empty($terms) )
			$terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);

		$links = array();

		foreach ( $terms as $term )
			$links[] = "<a href='" . attribute_escape(get_term_link($term, $taxonomy)) . "'>$term->name</a>";

		if ( $links )
			$taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
	}
	return $taxonomies;
}

/**
 * Retrieve all taxonomies of a post with just the names.
 *
 * @since 2.6
 * @uses get_object_taxonomies()
 *
 * @param int $post Optional. Post ID
 * @return array
 */
function get_post_taxonomies($post = 0) {
	$post =& get_post($post);

	return get_object_taxonomies($post);
}



}

//////////////////////   class from user.php //////////////
// WP_User_Search class
// by Mark Jaquith
/* //TODO:what is this?
if ( !class_exists('WP_User_Search') ) :
*/
class WP_User_Search {
	var $results;
	var $search_term;
	var $page;
	var $role;
	var $raw_page;
	var $users_per_page = 50;
	var $first_user;
	var $last_user;
	var $query_limit;
	var $query_sort;
	var $query_from_where;
	var $total_users_for_query = 0;
	var $too_many_total_users = false;
	var $search_errors;

	function WP_User_Search ($search_term = '', $page = '', $role = '') { // constructor
		$this->search_term = $search_term;
		$this->raw_page = ( '' == $page ) ? false : (int) $page;
		$this->page = (int) ( '' == $page ) ? 1 : $page;
		$this->role = $role;

		$this->prepare_query();
		$this->query();
		$this->prepare_vars_for_template_usage();
		$this->do_paging();
	}

	function prepare_query() {
		$wpdb = JWPBlog::getWpdb();
		$this->first_user = ($this->page - 1) * $this->users_per_page;
		$this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page);
		$this->query_sort = ' ORDER BY user_login';
		$search_sql = '';
		if ( $this->search_term ) {
			$searches = array();
			$search_sql = 'AND (';
			foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col )
			$searches[] = $col . " LIKE '%$this->search_term%'";
			$search_sql .= implode(' OR ', $searches);
			$search_sql .= ')';
		}

		$this->query_from_where = "FROM $wpdb->users";
		if ( $this->role )
		$this->query_from_where .= $wpdb->prepare(" INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%');
		else
		$this->query_from_where .= " WHERE 1=1";
		$this->query_from_where .= " $search_sql";

	}

	function query() {
		$wpdb = JWPBlog::getWpdb();
		$this->results = $wpdb->get_col('SELECT ID ' . $this->query_from_where . $this->query_sort . $this->query_limit);

		if ( $this->results )
		$this->total_users_for_query = $wpdb->get_var('SELECT COUNT(ID) ' . $this->query_from_where); // no limit
		else
		$this->search_errors = new WP_Error('no_matching_users_found', __('No matching users were found!'));
	}

	function prepare_vars_for_template_usage() {
		$this->search_term = stripslashes($this->search_term); // done with DB, from now on we want slashes gone
	}

	function do_paging() {
		if ( $this->total_users_for_query > $this->users_per_page ) { // have to page the results
			$args = array();
			if( ! empty($this->search_term) )
			$args['usersearch'] = urlencode($this->search_term);
			if( ! empty($this->role) )
			$args['role'] = urlencode($this->role);

			$this->paging_text = paginate_links( array(
				'total' => ceil($this->total_users_for_query / $this->users_per_page),
				'current' => $this->page,
				'base' => 'users.php?%_%',
				'format' => 'userspage=%#%',
				'add_args' => $args
			) );
		}
	}

	function get_results() {
		return (array) $this->results;
	}

	function page_links() {
		echo $this->paging_text;
	}

	function results_are_paged() {
		if ( $this->paging_text )
		return true;
		return false;
	}

	function is_search() {
		if ( $this->search_term )
		return true;
		return false;
	}
}

class Walker_Category_Checklist extends Walker{
	var $tree_type;
	var $db_fields;
	
	function __construct(){
		$this->tree_type = 'category';
		$this->db_fields = array('parent' => 'parent', 'id' => 'term_id');	
	}
	
	function start_lvl(&$output, $depth, $args) {
		$indent = str_repeat("\t", $depth);
		$output .= "$indent<ul class='children'>\n";
	}

	function end_lvl(&$output, $depth, $args) {
		$indent = str_repeat("\t", $depth);
		$output .= "$indent</ul>\n";
	}

	function start_el(&$output, $category, $depth, $args) {
		extract($args);

		$class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : '';
		$output .= "\n<li id='category-$category->term_id'$class>" . '<label for="in-category-' . $category->term_id . '" class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="post_category[]" id="in-category-' . $category->term_id . '"' . (in_array( $category->term_id, $selected_cats ) ? ' checked="checked"' : "" ) . '/> ' . wp_specialchars( wpbasic::apply_filters('the_category', $category->name )) . '</label>';
	}

	function end_el(&$output, $category, $depth, $args) {
		$output .= "</li>\n";
	}
}
?>